如何垂直居中文本重叠图像?

时间:2014-04-17 20:59:02

标签: html css

如何在图像上垂直居中显示文字?我已经对它的外观进行了设置但是我无法将文本集中在每个图像上,因为它们具有不同的高度。

我已经尝试过使用其他问题中提到的“top”属性和vertical-align以及方法,但似乎没有什么能适用于这种情况。

无论如何这可以实现吗?

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%;
}

4 个答案:

答案 0 :(得分: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代码为每个<p>计算css top属性,以使它们位于块的中间。

另一个纯css解决方案是稍微更改你的html代码,你必须添加100%/宽度100%的表高度并在<td>上设置一个vertical-align:middle,你应该在里面把段落。

答案 1 :(得分:0)

尝试line-heighttop:50%;margin-top://-the height of the Textblock

答案 2 :(得分:0)

您可以将line-height设置为100%,这会使线条与图像的高度相同,垂直居中。

JSFiddle

答案 3 :(得分: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>