这是最奇怪的事情,我以前多次使用过这种方法,但现在它似乎对我来说是坏的。
这是一个提供此方法作为答案的重复问题:
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>
最佳答案
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>
关于CSS保持纵横比不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901814/