CSS 这是使 <body> 最大宽度并居中的最佳方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11088938/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:13:53  来源:igfitidea点击:

Is this the best way to make the <body> max-width and centered?

css

提问by Clay Nichols

I want the content of a web page to be centered and max width of, say 900px.

我希望网页的内容居中且最大宽度为 900 像素。

From my research and testing, it looks like this is the way to do it, but I wanted to confirm:

从我的研究和测试来看,看起来是这样做的,但我想确认:

<body style="max-width:900px; text-align:center;margin-left:auto ;margin-right:auto">

Obviously, you'd put the stylein the CSS.

显然,您会将样式放在 CSS 中。

And I figure anybody with a big screen is going to have a fairly new browser.

而且我认为任何拥有大屏幕的人都会拥有一个相当新的浏览器。

采纳答案by David

CSS:

CSS:

body { width: 100%; text-align: center; }
#centerContainer { width: 900px; text-align: left; margin: 0px auto; }

HTML:

HTML:

<body>
  <div id="centerContainer">Content</div>
</body>

回答by Johann

Why use a wrapper unless and until you need it? I wouldn't wrap stuff nilly-willy just because you can, it adds up. Also, you can use the Body tag as a "free wrapper" if you want:

除非需要,否则为什么要使用包装器?我不会因为你可以就随意包装东西,它加起来。此外,如果需要,您可以将 Body 标记用作“免费包装器”:

CSS:

CSS:

html {
    margin:    0 auto;
    max-width: 900px;
}
body
{
    /* whatever you want */
}        

回答by Asif

Rather than make <body>centered, I would recommend to make a <div>as a wrapperor containerwith width: 900px.

我建议将 a作为包装器容器,而不是使<body>居中<div>width: 900px



HTML:

HTML:

<body>
   <div id="container">

   **Your Contents**

   </div>
</body>

CSS:

CSS:

body{
   width: 100%;
}
#container {
   width: 900px;
   margin: 0 auto;
}

回答by Mali

The way I do it is by creating a wrapper div that will hold your content on the page.

我这样做的方法是创建一个包装 div,它将您的内容保存在页面上。

CSS:

CSS:

#wrapper{margin:0 auto; width:900px;}

HTML:

HTML:

<div id="wrapper>

<!--content goes here-->

</div> <!--/wrapper-->

回答by callmedpit

Rather than doing it on body, I would create a "wrapper" div and style it this way:

而不是在身体上做它,我会创建一个“包装器”div并以这种方式设置它的样式:

<div style="width: 900px; margin: auto;">Content</div>