您不需要为此使用 JavaScript。您可以使用纯CSS。
padding-top 百分比是相对于包含块来解释的width。将其与子元素上的position:absolute相结合,您可以将几乎所有内容放入保留其纵横比的框中。
HTML:
<div class="aspectwrapper">
<div class="content">
</div>
</div>
CSS:
.aspectwrapper {
display: inline-block; /* shrink to fit */
width: 100%; /* whatever width you like */
position: relative; /* so .content can use position: absolute */
}
.aspectwrapper::after {
padding-top: 56.25%; /* percentage of containing block _width_ */
display: block;
content: '';
}
.content {
position: absolute;
top: 0; bottom: 0; right: 0; left: 0; /* follow the parent's edges */
outline: thin dashed green; /* just so you can see the box */
}
The display: inline-block
在底部边缘下方留出一点额外的空间.aspectwrapper
框,因此它下面的另一个元素不会与它齐平。使用display: block
将会摆脱它。
谢谢这个帖子 http://ansciath.tumblr.com/post/7347495869/css-aspect-ratio给小费!
另一种方法依赖于这样一个事实:当您仅调整图像的宽度或高度时,浏览器会尊重图像的纵横比。 (出于演示目的,我将让 google 生成一个 16x9 透明图像,但实际上您将使用自己的静态图像。)
HTML:
<div class="aspectwrapper">
<img class="aspectspacer" src="http://chart.googleapis.com/chart?cht=p3&chs=160x90" />
<div class="content">
</div>
</div>
CSS:
.aspectwrapper {
width: 100%;
position: relative;
}
.aspectspacer {
width: 100%; /* let the enlarged image height push .aspectwrapper's bottom edge */
}
.content {
position: absolute;
top: 0; bottom: 0; right: 0; left: 0;
outline: thin dashed green;
}