Html 如何在 body 标签中垂直和水平居中文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8959705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I center text vertically and horizontally in the body tag?
提问by 1.21 gigawatts
How do I center text vertically and horizontally to the center of the page?
如何将文本垂直和水平居中到页面中心?
For example, if I have this text, "Enter the codes".
例如,如果我有这个文本,“输入代码”。
Also, bonus related question, does it matter if it's text or an image? I ask because I may put an image to the left of the text.
另外,奖金相关的问题,是文字还是图片重要吗?我问是因为我可能会在文本的左侧放一张图片。
回答by Borealid
I'm not exactly sure what you mean by "center" (there are several definitions), but perhaps this will do what you want:
我不太确定你所说的“中心”是什么意思(有几个定义),但也许这会做你想要的:
<div class="myclass">Some text</div>
.myclass {
position: absolute;
left: 50%;
top: 50%;
}
It doesn't matter if it's text or an image - the browser just regards it as block content.
它是文本还是图像并不重要 - 浏览器只是将其视为块内容。
Note that text-align: center;
will center items horizontally within their container.
请注意,这text-align: center;
将使项目在其容器内水平居中。