我通常面臨的情況是,我需要顯示一組符合柔性容器內特定高寬比的縮略圖/圖像。我一直使用的方法是使用一個空白的,相對定位的img到正確的長寬比,而實際的圖像(未知比例)顯示在下面作爲絕對定位的圖像。在柔性容器中強制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 */
}
這一點,在我的愚見,似乎不是一個特別優雅的解決方案。所以我的問題是,如何在不使用空白 PNG或javascript的情況下實現同樣的效果?此外,它應該不用說,圖像不能扭曲。
記住:
的圖像的大小和縱橫比爲NOT已知(僅所需的寬高比是已知的,在這種情況下,是1:1)。
的容器本身是柔性在寬度/高度
長寬比必須保持相同(但是裁剪包含圖像的是允許的)
不需要JavaScript
否JAVASCRIPT。
這裏的一個Fiddle
你可以只將它們設置爲背景圖像,並使用'背景大小:cover'。 –
IE8或更低版本不支持背景大小,但如果這不是你的問題與詹姆斯唐納利的建議。你可能也想使用background-position:center;以及。 – MarkP