在div中垂直和水平居中文本 [英] Vertically and horizontally centering text within a div
问题描述
我有一个div,其中包含一个覆盖有文本的图形背景。我想把这个元素水平和垂直居中。但我不能得到文本垂直居中。到目前为止,我有以下代码:
I have a div that comprises a graphic background overlaid with text. I want to center this element horizontally and vertically. But I can't get the text to center vertically. So far, I have the following code:
<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技术
Using the table-cell/vertical-align technique I've seen often referenced elsewhere doesn't quite work.
推荐答案
假设它是 H3
我假设它是一个标题,所以它可能会是一行文本。如果是这种情况,只需将 h3
的 line-height
设置为容器的高度即可。
Given that it's an H3
i'm assuming it's a heading so it's probably gonna be one line of text. If that's the case just set the line-height
of the h3
to the height of the container.
如果是段落,您可以这样做:
If instead it's a paragraph you can do this:
#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)
}
不要将像素与百分比混合。
Don't mix pixels with percentages.
这篇关于在div中垂直和水平居中文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!