2013-06-26 34 views
0

我仍然在學習html和css,所以請保持溫柔,但我無法將文本居中放置在每個單獨的圖像容器(http://jsbin.com/uwolat/1/edit)上。我已經嘗試了50%的頂部和高度,但它並沒有限制到特定的父容器。任何幫助將不勝感激!垂直/水平居中文本在img容器

+2

'<!DOCTYPE HTML PUBLIC 「 - // W3C // DTD XHTML 1.0過渡// EN」「HTTP:/ /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd「>''ಠ_ಠ' –

+0

ŠimeVidas而不是臉上給他的反饋。他說他是新人,脫下你的高馬。 user2252219,SimeVidas說的是看看優化HTML5的HTML - 這裏有一個鏈接讓你開始:http://www.html5rocks.com/ – danielsan

回答

1

這裏是DEMO http://jsfiddle.net/yeyene/7bc7j/1/

給一個類.imgTitle所有的標題p標籤。所有這些都不需要單獨的ID。

以下腳本將垂直/水平居中對齊所有文本,用於任何寬度的文本,長或短。

JQUERY

$(document).ready(function() { 
    $('.img-container').each(function() { 
     // Get a reference to the image.  
     var img = $(this).find('img'); 
     var p = $(this).find('.imgTitle'); 

     // center the title 
     $(this).children('p.imgTitle').css({ 
      'top':((img.height() - p.height())/2) - 13, 
      'left':(img.width() - p.width())/2 
     }); 

     // Hide by default. 
     img.hide(); 

     $(this).hover(function() { 
      img.stop().fadeIn(50); 
     }, function() { 
      img.stop().fadeOut(1300); 
     }); 

    }); 
}); 

HTML

<div class="img-container"> 
    <img src="http://wallpaper-fun.ophibian.com/wallpapers/wallpaper_08.jpg" alt="a" width="100%" height="200" /> 
    <p class="imgTitle">Pure Waves</p> 
</div> 
0

嘗試設置

position:relative; text-align:center;

爲您的文本

+0

位置:relative會讓你在div中定位元素包含它 – danecando

0

的訣竅是在line-height

LIVE DEMO

不要重複你的自我,從你的p元素中刪除所有不需要的ID。
給一個類你<p>元素:<p class="description">Bla bla bla</p>

CSS:

.img-container 
{ 
    /*display: block;*/ /* DIV is already BLOCK level element*/ 
    /*float: inline;*/ /* Back to school ;) */ 
    margin:0; 
    width: 100%; 
    height: 200px; 
    line-height:185px; /* PLAY HERE */ 
    background: #e5e5e5; 
    border-bottom:1px solid #444; /* added just for demo */ 

    text-align:center; /* to align inner P text */ 
} 

.description 
{ 
    position: absolute; 
    width:100%;   
    /*height:200px;*/ /* if needed? */ 
    color: #000; 
    font-family: 'Open Sans', sans-serif; 
    font-weight: 600; 
    text-transform: uppercase; 
    letter-spacing: 2px; 
    font-size: 13px; 
} 
+0

謝謝你們!真的很感激你的幫助。不知道這個論壇是否使用代表或什麼,但讚不絕口。 :) – user2252219