2013-11-21 51 views
0

我有兩個不同的寬度和高度的圖像,需要在圖像框中居中定位。這裏是HTML和CSS的例子。如何使用css定位不同大小的圖像?

<div class="box"> 
    <div class='image'> 
     <img alt="" src="image.jpg"/> 
    </div> 
</div> 

.box { 
    max-width: 970px; 
    height: 440px; 
} 
.box img { 
    max-width: 100%; 
    position: absolute; 
    bottom: 8px; 
    margin-left: auto; 
    margin-right: auto; 
} 

此代碼適用於精確寬度和高度的大圖像。但是當一個較小的圖像放置在圖像框中時,該圖像位於右下角。我怎樣才能使兩個圖像中心底部?

感謝任何人的幫助!

回答

0

在這裏,你去...我會盡力解釋,因爲我們去,但簡短的回答,a fiddle

.box { 
    /* Just so I could see the parent */ 
    background-color: #bada55; 
    max-width: 970px; 
    height: 440px; 
    /* Needed to make this element positional (so it will contain the absolutely positioned child */ 
    position: relative; 
    /* Yep, center wasn't necessary here... */ 
} 
.box .image { /* move this to the image wrapper */ 
    position: absolute; 
    bottom: 8px; 
    /* Force full width */ 
    left: 0; 
    right: 0; 
    /* Center contents (the image) */ 
    text-align: center; 
} 
img { 
    max-width: 100%; 
} 
+0

謝謝菲利普斯。這很好。但是,我忘了提及該圖像是在外部html文檔的iframe中,該文檔的固定寬度爲989 x 600,並且您編碼圖像的位置居中正確,但在.box內不在iframe內:(在我發佈這個問題之前,我忘了提及這個問題,因此,我所做的是將.box的高度設置爲495px,並且這種方式將圖像相對於iframe進行了定位,你會怎麼做? –

+0

因此,如果結構是iframe> .box> .image> IMG只是採取的立場:相對關閉.box。 – philwills

+0

是的。它工作得很好!謝謝菲利普斯!非常感謝。 –

0

我發現這招語義工作得很好(沒有任何絕對位置)

.box { 
margin: 0; 
text-align: center; 
max-width: 970px; 
height: 440px; 
border:2px solid red; 
} 

.box .something-semantic { 
display: table; 
width: 100%; 
height: 100%; 
} 

.box .something-else-semantic { 
display: table-cell; 
text-align: center; 
vertical-align: bottom; 
} 

HTML

<div class="box"> 
<div class="something-semantic"> 
<div class="something-else-semantic"> 
    <img src="" width="50" height="40"/> 
    <img src="" width="120" height="70"/> 
</div> 
</div> 
</div> 

fiddle here.

+0

這基本上是使用表來格式化...即使你沒有使用表標記,你基本上使該div與表的樣式(比使用表,但仍然不好)。 – philwills

+0

謝謝@buddweeze! –

相關問題