如何将100%宽度的图像构图为锁定比例?

时间:2015-01-28 01:21:40

标签: html css

我希望在16:9比例的框架内显示100%宽度的图像。图像应在帧内居中,并响应屏幕大小调整。理想情况下,我希望能够只使用CSS。

2 个答案:

答案 0 :(得分:0)

结合多个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;
}

此解决方案结合了以下问题中列出的方法:

How to keep image aspect ratio inside a %width div?

Scale a div to fit in window but preserve aspect ratio

答案 1 :(得分:0)

.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
}

less mixin:

.aspectRatio(@widthAspect, @heightAspect) {
    @aspect: @heightAspect/@widthAspect * 100;
    max-width: 100%;

    &:before {
        content: '';
        display: block;
        width: 100%;
        padding-bottom: ~"@{aspect}%";
    }
}