2013-06-26 35 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