我经常遇到的情况是,我需要在一个灵活的容器中显示一组符合特定宽高比的缩略图/图像。我一直用来实现这一点的方法是使用一个空白的、相对定位的 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 */
}
在我看来,这似乎不是一个特别优雅的解决方案。所以我的问题是,如何在不使用 blank PNG 或 javascript 的情况下实现相同的效果?另外,不言而喻,图像不能失真。
记住:
图像大小和纵横比未知(只知道所需的纵横比,在本例中为 1:1)。
容器本身的宽度/高度灵活
宽高比必须保持不变(但允许裁剪包含的图像)
没有javascript
没有 JAVASCRIPT。
这是一个 Fiddle
最佳答案
借自 Elastic Videos example
要求:
- 所有图像的纵横比都相同(尽管这可以通过额外的类进行扩展)
- 小猫
标记:
<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>
CSS:
.thumbnail {
display: inline-block;
position: relative;
float: left;
width: 33%;
overflow: hidden;
height: 0;
}
.thumbnail img {
position: absolute;
left: 0;
bottom: 0;
right: 0;
top: 0;
width: 100%;
height: auto;
}
/* Aspect Ratio 1:1 */
.thumbnail {
padding-top: 33%;
}
如果您知道所有图像的高度都相同,则可以进行相应裁剪:
/* If you know all the images are the same height */
.thumbnail img {
top: -50%;
}
哦,它支持不同高度的图像:
关于html - 强制灵活容器内的 img 以更正比例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21476336/