我正在做一个元素,我希望我的网页在调整大小或在任何设备上查看时都能保持其样式和纵横比。我曾尝试在 CSS 上使用位置属性 (position:fixed;),但它不起作用。如何使用 CSS 完成此操作?
figure {
width: 36%;
margin: 8px auto;
}
div.relative_div {
width: 100%;
padding-bottom: 56.25%; /* 16:9 */
position: relative;
background: black;
}
div.relative_div > div {
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
color: white;
font-size: 24px;
text-align: center;
}
<html>
<body>
<figure>
<div class="relative_div">
<div>Relative Aspect Ratio </div>
</div>
</figure>
</body>
</html>
正如您在 CSS 中看到的,我们所要做的就是将一个 100% 宽度的元素嵌套在“响应式”基于百分比宽度的父元素中,然后根据我们要保持的比率。要计算任何宽高比所需的百分比,我们可以使用以下公式:
B/(A/100) = C%
所以对于 16:9(其中 16 是 A,9 是 B):
9/.16 = 56.25 (%)
我是一名优秀的程序员,十分优秀!