这是最奇怪的事情,我以前已经使用过这种方法很多次了,但是现在看来对我来说很困难。
这是一个重复的问题,提供了此方法作为答案:
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>
最佳答案
这实际上是正确的行为。您应将子级的宽度设为100%,并与父级一起控制尺寸。
例:
.parent {
width: 200px;
}
.child {
width: 100%;
background: red;
padding-top: 100%;
}
<div class="parent">
<div class="child"></div>
</div>
这是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
}
<div class="parent">
<div class="child"></div>
</div>
长宽比-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
}
<div class="parent">
<div class="child"></div>
</div>
长宽比-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
}
<div class="parent">
<div class="child"></div>
</div>
您可以在此处找到完整的文章:
https://css-tricks.com/aspect-ratio-boxes/
关于css - CSS保持宽高比不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49901814/