Html 如何将正文居中放置在页面上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10872688/
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 to center body on a page?
提问by Ryan Peschel
I'm trying to center the body element on my HTML page.
我试图将 body 元素放在我的 HTML 页面上。
Basically, in the CSS I set the body element to be display: inline-block;
so that it is only as wide as its contents. That works fine. However, margin: 0px auto;
doesn't center it on the page.
基本上,在 CSS 中,我将 body 元素设置display: inline-block;
为仅与其内容一样宽。这很好用。但是,margin: 0px auto;
不会在页面上居中。
Does anyone know how to fix this? I want the big blue square to be centered on the page, not floating to the left like it is now.
有谁知道如何解决这一问题?我希望蓝色的大方块位于页面的中心,而不是像现在这样向左浮动。
Here's my CSS:
这是我的 CSS:
body {
display: inline-block;
margin: 0px auto;
text-align: center;
}
回答by Freakishly
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
这将适用于大多数浏览器,包括 IE。
回答by Madara's Ghost
Also apply text-align: center; on the html element like so:
还应用 text-align: center; 在 html 元素上,像这样:
html {
text-align: center;
}
A better approach though is to have an inner container div, which will be centralized, and not the body.
更好的方法是有一个内部容器 div,它将是集中的,而不是主体。
回答by SRN
You have to specify the width to the body for it to center on the page.
您必须指定正文的宽度才能使其在页面上居中。
Or put all the content in the div and center it.
<body>
<div>
jhfgdfjh
</div>
</body>?
div {
margin: 0px auto;
width:400px;
}
?
?
回答by DardanM
For those that doknow the width, you could do something like
对于那些做知道宽度,您可以做类似
div {
max-width: ???px; //px,%
margin-left:auto;
margin-right:auto;
}
I also agree about not setting text-align:centeron the body because it can mess up the rest of your code and you might have to individually set text-align:lefton a lot of things either then or in the future.
我也同意不要在 body 上设置text-align:center,因为它可能会弄乱您的其余代码,并且您可能必须在当时或将来在很多事情上单独设置text-align:left。