在div中垂直和水平居中文本

时间:2012-02-24 12:32:01

标签: css

我有一个包含覆盖文字的图形背景的div。我希望水平和垂直居中这个元素。但我不能让文本垂直居中。到目前为止,我有以下代码:

<div id="step">
    <div id="background">
        <img src="buttonbackground.png" class="stretch" alt="" />
    </div>
    <div>
       <h3>some text</h3>
    </div>
</div>

在CSS中:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px;
    z-index: -1;
}

#step {
    text-align:center;
    color:white;
}

.stretch {
    width:200px;
    height:40px;
}

使用我在其他地方经常引用的table-cell / vertical-align技术并不常用。

2 个答案:

答案 0 :(得分:2)

鉴于它是H3,我假设它是一个标题,所以它可能是一行文字。如果是这种情况,只需将line-height的{​​{1}}设置为容器的高度。

如果是段落,你可以这样做:

h3

}

请勿将像素与百分比混合。

答案 1 :(得分:0)

尝试:

#step {
    text-align: center;
    vertical-align: center;
    color: white;
    height: 40px;
}

编辑:

或者,您可以尝试将#background的高度明确设置为40px而不是100%。它应该达到同样的效果。

相关问题