Just create a wrapper <div>
with a percentage value for padding-bottom
, like this:
(只需为padding-bottom
创建具有百分比值的包装器<div>
,如下所示:)
div { width: 100%; padding-bottom: 75%; background: gold; /** <-- For the demo **/ }
<div></div>
It will result in a <div>
with height equal to 75% of the width of its container (a 4:3 aspect ratio).
(这将导致<div>
的高度等于其容器宽度的75%(长宽比为4:3)。)
This relies on the fact that for padding :
(这取决于以下事实:)
The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org , emphasis mine)
(相对于生成的盒子的包含块的宽度计算百分比(来源: w3.org ,强调我的))
Padding-bottom values for other aspect ratios and 100% width :
(其他长宽比和100%宽度的填充底部值:)
aspect ratio | padding-bottom value
--------------|----------------------
16:9 | 56.25%
4:3 | 75%
3:2 | 66.66%
8:5 | 62.5%
Placing content in the div :
(将内容放在div中:)
In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:
(为了保持div的长宽比并防止其内容拉伸,您需要添加一个绝对定位的子级,并使用以下方法将其拉伸到包装的边缘:)
div.stretchy-wrapper {
position: relative;
}
div.stretchy-wrapper > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
}
Here's a demo and another more in depth demo
(这是一个演示 ,还有另一个更深入的演示)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…