水平和垂直中心文本在html [英] Horizontal and vertical center text in html
问题描述
我有一个背景图片需要水平和垂直居中的div。
I have a div with a background image that needs to be centered horizontally and vertically. On top of that image, I also want to display a 1-line text, also centered horizontally and vertically.
我设法使图像居中,但文字是不垂直居中。我认为vertical-align:middle会做的。
I managed to get the image centered, but the text is not centered vertically. I thought vertical-align:middle would do the trick.
这是代码我有:
<div style="background: url('background.png') no-repeat center; width:100%; height:100%; text-align:center;">
<div style="color:#ffffff; text-align: center; vertical-align:middle;" >
Some text here.
</div>
</div>
有任何想法吗?
解决方法:我实际上使用表来工作。 (我可能会被诅咒到地狱由HTML社区。)有没有任何重要的理由不使用这个btw?我仍然对使用divs的解决方案感兴趣。
Workaround: I actually got this to work by using a table. (I'll probably be cursed to hell by the HTML community.) Is there any significant reason not to use this btw? I'm still interested in the solution using divs though.
<table width="100%" height="100%">
<tr>
<td align="center" style="background: url('background.png') no-repeat center; color:#ffffff;">Some text here.</td>
</tr>
</table>
推荐答案
块元素的水平居中传统上是这样做的:
Horizontal centering of a block element is traditionally done this way:
div.inner { margin: 0 auto; }
注意:上述操作将无法在IE中使用怪异模式因此始终在文档顶部放置 DOCTYPE
,以强制其进入符合标准的模式。
Note: the above won't work with IE in quirks mode so always put a DOCTYPE
at the top of your document to force it into standards compliant mode.
垂直居中更加繁琐。请参见 CSS中的垂直居中
Vertical centering is much more tedious. See Vertical Centering in CSS
这篇关于水平和垂直中心文本在html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!