Html 将柔性容器内的img强制至正确的比率

Html 将柔性容器内的img强制至正确的比率,html,css,Html,Css,我通常面临的情况是,我需要在一个灵活的容器中显示一组符合特定纵横比的缩略图/图像。我一直在使用的方法是使用一个空白的、相对定位的img来强制执行正确的纵横比,而真实图像(未知比例)在下面显示为绝对定位的图像 例如: HTML <div class="gallery-container"> <div class="thumbnail"> <!-- ordinarily I'd use a transparent PNG, but I'm bei

我通常面临的情况是,我需要在一个灵活的容器中显示一组符合特定纵横比的缩略图/图像。我一直在使用的方法是使用一个空白的、相对定位的img来强制执行正确的纵横比,而真实图像(未知比例)在下面显示为绝对定位的图像

例如:

HTML
<div class="gallery-container">
    <div class="thumbnail">
        <!-- ordinarily I'd use a transparent PNG, but I'm being lazy... -->
        <img src="http://placekitten.com/100/100" alt="Placeholder" class="blank-img" />
        <!-- Above img forces correct ratio -->
        <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
    </div>
    <div class="thumbnail">
        <img src="http://placekitten.com/100/100" alt="Placeholder" class="blank-img" />
        <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
    </div>
    <div class="thumbnail">
        <img src="http://placekitten.com/100/100" alt="Placeholder" class="blank-img" />
        <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
    </div>
</div>

CSS
.thumbnail {
    display: inline-block;
    position: relative;
    float: left;
    width: 33%;
    overflow: hidden;
}
.thumbnail img {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: auto;
}
.thumbnail .blank-img {
    position: relative;
    width: 100%;
    height: auto;
    opacity: 0; /* Not necessary for a blank png, but this is easier than importing resources in Fiddle */
}
HTML
CSS
.缩略图{
显示:内联块;
位置:相对位置;
浮动:左;
宽度:33%;
溢出:隐藏;
}
.缩略图像{
位置:绝对位置;
排名:0;
左:0;
宽度:100%;
高度:自动;
}
.缩略图.空白图像{
位置:相对位置;
宽度:100%;
高度:自动;
不透明度:0;/*对于空白png不是必需的,但这比在Fiddle中导入资源更容易*/
}
在我看来,这似乎不是一个特别优雅的解决方案。所以我的问题是,如果不使用空白的PNG或javascript,如何实现相同的效果?而且,不用说,图像不能被扭曲

记住:

  • 图像大小和纵横比未知(只有所需的纵横比已知,在本例中为1:1)

  • 容器本身在宽度/高度上是灵活的

  • 纵横比必须保持不变(但允许裁剪包含的图像)

  • 没有javascript

  • 没有JAVASCRIPT


  • 这是从Elastic视频中借来的

    要求:

    • 所有图像的所需纵横比相同(尽管这可以通过额外的类进行扩展)
    • 小猫
    标记:

    <div class="gallery-container">
        <div class="thumbnail">
            <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
        </div>
        <div class="thumbnail">
            <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
        </div>
        <div class="thumbnail">
            <img src="http://placekitten.com/200/400" alt="Lookit dah kitty!" />
        </div>
    </div>
    
    例如:

    如果您知道所有图像的高度相同,则可以相应地进行裁剪:

    /* If you know all the images are the same height */
    .thumbnail img {
       top: -50%;
    }
    
    例如:

    哦,它支持不同高度的图像:


    示例:

    您可以将它们设置为背景图像,并使用
    背景大小:cover
    。IE8或更低版本不支持背景大小,但如果这不是您的问题,请使用James Donnelly的建议。您可能还希望使用背景位置:中心;还有。对不起,我应该澄清一下,图像本身的纵横比是未知的。这实际上是一个由CMS控制的映像引起的问题(客户端不可信)。
    /* If you know all the images are the same height */
    .thumbnail img {
       top: -50%;
    }