2013-02-27 28 views
3

我有一個基於百分比的圖。在那個盒子裏,我有一個透明背景的圖像。我需要水平居中,並將其固定在容器的底部,同時允許頂部從容器中脫出(參見圖片)。水平居中放置圖像並在寬度未知時垂直放置在底部的div內

我可以使用絕對定位將其固定在底部並突破頂部,但我無法使其居中。有沒有辦法做到這一點,當我不知道圖像的寬度和容器的寬度是靈活的?顯示:表格有可能嗎?

example 我的代碼:

<figure class="feature"> 
<a href="#"> 
    <img src="image" /> 
    <p class="title-bar">Caption</p> 
</a> 
</figure> 

.figure { position: relative; width: 50%; } 
.figure img { position: absolute; bottom: 0; } 
+0

是對圖像可變的寬度? – Mooseman 2013-04-11 20:28:42

+0

@mooseman是的,圖像的寬度也是可變的。 – artmem 2013-04-12 00:11:47

回答

3

請,檢查這個小提琴,有2種型號居中的圖像

http://jsfiddle.net/GSKFD/

標記是這兩種方法同樣

<figure> 
<a href=""> 
    <img src="http://placekitten.com/200/300" alt="" /> 
</a> 
</figure> 

大將風範

img{ 
     vertical-align: bottom; 
    } 

第一變型

figure{ 
position: relative; 
width: 50%; 
height: 300px; 
background: #cad; 
} 
figure a{ 
    position: absolute; 
    bottom: 0; 
    left: 50%; 
} 
figure img{ 
    position: relative; 
    left: -50%; 
} 

,第二個

figure{ 
    position: relative; 
    width: 50%;  
    height: 300px; 
    background: #cad; 
} 
figure a{ 
    position: absolute; 
    width: 100%; 
    left: 0; 
    bottom: 0; 
    text-align: center; 
} 
+0

獲獎,因爲它的HTML和CSS稍微比@ Deborah的答案簡潔。 – 2013-04-15 22:22:19

0

基本上你需要做一個左:50%,則保證金左:-whatever圖像的寬度。這將把它定位在你的相對分區中。我的例子假定你不知道圖像的寬度。

http://jsfiddle.net/rVRT4/2/ http://jsfiddle.net/rVRT4/2/embedded/result/

$(document).ready(function(){ 
    var width = $(".figure img").width(); 
    $(".figure img").css("margin-left", -(width/2));  
}); 

.figure { position: relative; width: 50%; height: 500px;} 
.figure img { position: absolute; bottom: 0; left:50%;} 

<div class="figure"> 
<a href="#"> 
    <img src="http://i.stack.imgur.com/4TtEY.jpg" /> 
    <p class="title-bar">Caption</p> 
</a> 
</div> 
+0

有沒有一種純CSS的方式來做到這一點,沒有JavaScript? – 2013-04-11 21:09:52

3

你可以用純CSS做到這一點,但你需要兩個額外的div來保存和元素的位置。

這裏的CSS:

.featureHolder { 
    position: relative; 
    /* height can be anything */ 
    height: 200px; 
} 
.feature { 
    margin: 0; 
    overflow: visible; 
    /* width can be anything */ 
    width: 60%; 
    height: 100px; 
    background: #cccccc; 
    position: absolute; 
    bottom: 0; 
} 
.imageHolder { 
    text-align: center; 
    width: 100%; 
    position: absolute; 
    bottom: 0; 
} 
img { 
    margin-bottom: -5px; 
} 

這裏的HTML:

<div class="featureHolder"> 
    <figure class="feature"> 
    <div class="imageHolder"> 
     <a href="#"> 
      <img src="img" /> 
     </a> 
    </div> 
    <a href="#" class="title-bar">Caption</a> 
    </figure> 
</div> 

標題也可定位在同一標籤的圖像中,但在這個例子中它分離出來,所以我沒不必惹它。

下面是JSFiddle中的演示 - give .feature任意寬度,img仍然居中。 (順便說一下你的CSS不正確 - 它應該是'figure'或者'.feature',但不能是'.figure',因爲figure是類名'feature'的元素。)

相關問題