2012-02-24 117 views
0

我有一个包含图形背景覆盖文本的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; 
} 

使用表细胞/垂直对齐技术我见过其他地方常常引用完全不是那么回事。

回答

1

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

相反,如果它是一个段落,你可以这样做:

#centeredDiv { 
    position:absolute; 
    top: 50%; 
    left: 50% 
    margin-top:-20px ;(half the height of the container) 
    margin-left: -100px; (half the width of the container) 

}

不要用百分比混合像素。

0

尝试:

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

编辑:

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