这是最奇怪的事情,我以前曾多次使用过这种方法,但现在看来它似乎已经破裂了。
这是一个重复的问题,提供此方法作为答案:
Maintain the aspect ratio of a div with CSS
但由于某些未知原因,它在Firefox和Chrome中对我不利。根据我可以收集的内容,它根据我正在应用样式的元素的父级计算填充...
在这种情况下,它不会查看.test
,而是查看.parent
来计算填充:
.parent {
width: 200px;
}
.test {
width: 50px;
background: red;
padding-top: 100%;
}
<div class='parent'>
<div class='test'></div>
</div>
答案 0 :(得分:2)
CSS 有一个属性
.square {
aspect-ratio: 1 / 1;
width: 100px;
background: grey;
padding: 10px;
color: white;
}
<div class="square">a sqaure</div>
更新:
还有另一种方法,如果您的支持绝对至关重要,并且您无法忍受 Firefox 不受支持,那么您就可以了。但它有点笨拙。
div {
width: 5em;
height: 5em;
font-size: 3vw; background: grey; padding: 0.5em;}
/*em is relative to font-size so you could use that and vw is veiwport width where 100 is all of the veiwport. the size of the shape is now 5 * 3vh*/
<div>hello</div>
答案 1 :(得分:1)
这实际上是正确的行为。您的目的是让孩子100%宽度并控制父母的大小。
示例:
.parent {
width: 200px;
}
.child {
width: 100%;
background: red;
padding-top: 100%;
}
&#13;
<div class="parent">
<div class="child"></div>
</div>
&#13;
这是一个很好的CSS-Tricks方法,它可以帮助您获得所需比例所需的正确填充:
宽高比 - 2:1
.parent {
width: 200px;
}
.child {
width: 100%;
background: red;
padding-top: calc(1 / 2 * 100%); // will give you an aspect ratio of 2:1
}
&#13;
<div class="parent">
<div class="child"></div>
</div>
&#13;
宽高比 - 3:1
.parent {
width: 200px;
}
.child {
width: 100%;
background: red;
padding-top: calc(1 / 3 * 100%); // will give you an aspect ratio of 3:1
}
&#13;
<div class="parent">
<div class="child"></div>
</div>
&#13;
宽高比 - 16:9
.parent {
width: 200px;
}
.child {
width: 100%;
background: red;
padding-top: calc(9 / 16 * 100%); // will give you an aspect ratio of 16:9
}
&#13;
<div class="parent">
<div class="child"></div>
</div>
&#13;
你可以在这里找到完整的文章: https://css-tricks.com/aspect-ratio-boxes/