当我给图像指定百分比宽度或高度时,它只会增长/缩小,保持其纵横比,但如果我想要与另一个元素相同的效果,是否可以使用百分比将宽度和高度绑定在一起?
您可以使用纯 CSS 来做到这一点;不需要 JavaScript。这利用了(有点违反直觉的)事实:padding-top百分比是相对于包含块的width http://www.w3.org/TR/CSS21/box.html#propdef-padding-top。这是一个例子:
.wrapper {
width: 50%;
/* whatever width you want */
display: inline-block;
position: relative;
}
.wrapper:after {
padding-top: 56.25%;
/* 16:9 ratio */
display: block;
content: '';
}
.main {
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
/* fill parent */
background-color: deepskyblue;
/* let's see it! */
color: white;
}
<div class="wrapper">
<div class="main">
This is your div with the specified aspect ratio.
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)