使用CSS维持div的宽高比 [英] Maintain the aspect ratio of a div with CSS

查看:241
本文介绍了使用CSS维持div的宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个div,可以随着窗口宽度的改变而改变其宽度/高度。

I want to create a div that can change its width/height as the window's width changes.

有任何CSS3规则允许高度根据

Are there any CSS3 rules that would allow the height to change according to the width, while maintaining its aspect ratio?

我知道我可以通过JavaScript来做到这一点,但我宁愿只使用CSS。

I know I can do this via JavaScript, but I would prefer using only CSS.

推荐答案

只需使用 padding-bottom 的百分比值创建包装器< div>

Just create a wrapper <div> with a percentage value for padding-bottom, like this:

div {
  width: 100%;
  padding-bottom: 75%;
  background:gold; /** <-- For the demo **/
}

<div></div>

导致< div> ,高度等于其容器宽度的75%(4:3宽高比)。

It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

这取决于以下事实:对于填充:

This relies on the fact that for padding :


百分比是相对于生成的框的包含块[...](来源: w3.org ,着重我的)

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

其他长宽比和100%宽度的底部值: p>

Padding-bottom values for other aspect ratios and 100% width :

aspect ratio  | padding-bottom value
--------------|----------------------
    16:9      |       56.25%
    4:3       |       75%
    3:2       |       66.66%
    8:5       |       62.5%






为了保持div的宽高比并防止它的内容被拉伸,你需要添加一个绝对定位的孩子,包装器的边缘:

In order to keep the aspect ratio of the div and prevent it's content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

div.stretchy-wrapper {
  position: relative;
}

div.stretchy-wrapper > div {
  position: absolute;
  top: 0; bottom: 0; left: 0; right: 0;
}

演示 和另一个更深入的演示

这篇关于使用CSS维持div的宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆