2014-04-17 38 views
0

如何在圖像上垂直居中文字?我已經對它的外觀做了一個設置,但是由於它們有不同的高度,所以我無法讓文字集中在每張圖片上。如何垂直居中文字重疊圖像?

我已經嘗試使用其他問題中提到的「top」屬性和垂直對齊方法,但似乎沒有任何工作適用於這種情況。

反正有這個可以實現嗎?

的的jsfiddle可以在這裏找到:http://jsfiddle.net/Sf3RX/2/

HTML

<div class="column"> 
<div class="image"> 
    <img src="/"> 
    <p class="info">cats 
     <br><span>#Photography</span> 
    </p> 
</div> 

CSS

.image { 
    position: relative; 
    width: 25%; 
    text-align: center; 
} 

img { 
    width: 100%; 
} 

p.info { 
    position: absolute; 
    width: 100%; 
    z-index: 10; 
    top: 25%; 
} 
+0

是圖像大小的動態,或者你能解決這個問題? – dsfg

回答

1

如果要實現這一結果http://jsfiddle.net/paulalexandru/MSfPs/所有你需要做的是:

調整你的CSS是這樣的:

p.info { 
    position: absolute; 
    width: 100%; 
    z-index: 10; 
    top: 25%; 
    margin: 0; 
    padding: 0; 
} 

,並添加這段JavaScript代碼:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $(".image").each(function() { 
      var height_image = $(this).find('img').height(); 
      var height_p = $(this).find('p.info').height(); 

      var rest = height_image - height_p; 
      $(this).find('p.info').css('top', rest/2); 
     }); 
    }); 
</script> 

javascript代碼計算t他爲每個<p>頂級財產,以便他們在塊的中間。

另一個純粹的CSS解決方案是改變你的HTML代碼一點點,你必須添加一個表格高度100%/寬度100%,並在<td>上設置一個垂直對齊:中間和它應該把段落。

+0

以上解決方案工作正常。 – dsfg

+0

此解決方案完美運作!遇到了一些麻煩得到它與實際網頁的工作,但我想它了。非常感謝! – torxnl

0

嘗試line-height,或top:50%;margin-top://-the height of the Textblock

0

您可以將line-height設置爲100%,這將使圖像的高度與圖像垂直居中。

JSFiddle

+1

不,這不起作用。 – paulalexandru

0
<style> 
body{ 
padding: 0; 
margin: 0; 
    margin:0px auto; 
} 
#main{ 
    position: relative; 
width:500px; 
height:500px; 
} 
#abc{ 
    text-align:center; 
background-color:#0F0; 
height:250px; 
display: table; 
width: 100%; 
} 

#abc span { 
    vertical-align:middle; 
display: table-cell; 
} 
</style> 
<div id="main"> 
    <div id="abc"> 
     <span>asdfasdfafasdfasdf<br/> sdfjdsl flkjdsflk sjdflkjdsf </span> 
</div> 
</div>