2014-01-31 20 views
1

我通常面臨的情況是,我需要顯示一組符合柔性容器內特定高寬比的縮略圖/圖像。我一直使用的方法是使用一個空白的,相對定位的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的情況下實現同樣的效果?此外,它應該不用說,圖像不能扭曲。

記住:

  1. 的圖像的大小和縱橫比爲NOT已知(僅所需的寬高比是已知的,在這種情況下,是1:1)。

  2. 的容器本身是柔性在寬度/高度

  3. 長寬比必須保持相同(但是裁剪包含圖像的是允許的)

  4. 不需要JavaScript

  5. 否JAVASCRIPT。

這裏的一個Fiddle

+2

你可以只將它們設置爲背景圖像,並使用'背景大小:cover'。 –

+0

IE8或更低版本不支持背景大小,但如果這不是你的問題與詹姆斯唐納利的建議。你可能也想使用background-position:center;以及。 – MarkP

回答

1

從彈性畫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%; 
} 

例子:http://jsfiddle.net/y6Ytz/

如果你知道所有的圖像都具有相同的高度,然後你可以裁剪相應:

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

例:http://jsfiddle.net/LWZY8/

哦,它支持因人而異高度的圖像:

例子:http://jsfiddle.net/3S5T7/

+0

對不起,我應該澄清一下,圖像本身的寬高比是未知的。這實際上是由CMS控制的圖像引起的問題(並且客戶端不可信)。 – monners