【发布时间】:2015-01-28 09:26:39
【问题描述】:
我希望在 16:9 比例的框架内显示 100% 宽度的图像。图像应在框架内居中并响应屏幕大小调整。理想情况下,我希望能够只使用 CSS 来做到这一点。
【问题讨论】:
我希望在 16:9 比例的框架内显示 100% 宽度的图像。图像应在框架内居中并响应屏幕大小调整。理想情况下,我希望能够只使用 CSS 来做到这一点。
【问题讨论】:
结合多个 SO 答案,我能够使用以下样式使其工作。框架的尺寸在 .grid_6 中设置为 100% 宽度,在 .grid_6::after 中设置为 56.25% 高度。
JS 小提琴:http://jsfiddle.net/stroz/fz2ez4uv/2/
HTML
<div class="thumb grid_6">
<img src="http://placekitten.com/g/200/300" />
</div>
CSS
.grid_6 {
width: 100%;
overflow:hidden;
position:relative;
}
.grid_6::after {
padding-top: 56.25%; /* percentage of containing block _width_ */
display: block;
content: '';
}
.thumb img {
display: block;
width:100%;
height:auto;
position: absolute;
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
}
此解决方案结合了以下问题中概述的方法:
【讨论】:
.aspect { max-width: 100%; }
.aspect.dims16by9:before {
content: '';
display: block;
width: 100%;
padding-bottom: 56.25%; // 9/16
}
.aspect.dims4by3:before {
content: '';
display: block;
width: 100%;
padding-bottom: 75%; // 9/16
}
少混入:
.aspectRatio(@widthAspect, @heightAspect) {
@aspect: @heightAspect/@widthAspect * 100;
max-width: 100%;
&:before {
content: '';
display: block;
width: 100%;
padding-bottom: ~"@{aspect}%";
}
}
【讨论】: