2014-05-20 51 views
1

我正在嘗試將圖像放在一個div中,該div響應地縮放,並且始終爲方形響應方格內的垂直中心圖像

JSFiddle

我已經得到了總是方部分工作歸功於真棒CSS-only option here

CSS:

.thumbnail_container { 
    position: relative; 
    width: 25%; 
    padding-bottom: 25%; 
    float:left; 
} 

.thumbnail { 
    position:absolute; 
    width:100%; 
    height:100%; 
    text-align:center; 
} 

HTML:

<div class="thumbnail_container vcenter-ext"> 
    <div class="thumbnail vcenter-int"> 
     <img src="http://placehold.it/200x300" /> 
    </div> 
</div> 

而且在一個div V型排列通常是很直向前:

.vcenter-ext { display: table;} 
.center-int { display: table-cell; vertical-align: middle;} 

但最終,我似乎無法將它們一起使用......任何人都可以指出我的問題?!​​?

+0

如果你不關心[=

+0

你可以看看這個答案,響應正方形的內容:http://stackoverflow.com/a/20457076/1811992它描述了一個很好的技術,以響應正方形中心的內容。 –

回答

4

解決你的問題,你必須刪除display: table;display: table-cell; vertical-align: middle;和必須補充一點:

.thumbnail img { 
    position: absolute; 
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    margin: auto; 
} 

垂直居中圖像。 This article解釋了我使用的方法(絕對定位和拉伸)。

注:我的代碼工作,因爲.thumbnailimg標籤的父母,有一個position: absolute屬性。

您可以看看this fiddle來查看結果。

+0

這就像一個魅力 - 謝謝! –

0

是這樣的嗎?

HTML:

<div> 
<img src="http://placehold.it/200x300" /> 

的CSS:

body{margin:0px auto;padding:0;text-align:center;} 
div{padding:80px;width:25%;margin:0px auto;background:green;} 
img{width:80%;margin:0px auto;padding:0;} 

http://jsfiddle.net/8Fjsd/

另外:

vcenter-int不存在