简体   繁体   English

如何设置身体宽度并将其水平居中

[英]how to set body width and center it horizontally

I remember - it was possible earlier - to set body width and center it horizontally - like in the example below我记得 - 之前有可能 - 设置身体宽度并将其水平居中 - 如下例所示
now - seems it is not possible this way现在 - 似乎不可能这样
how to do it?怎么做?

 body{ width:99px; margin:0 auto; height:100vh; background:orange; }

Use a container element and set a specific max-width.使用容器元素并设置特定的最大宽度。 A common width many websites use is 960px.许多网站使用的常见宽度是 960 像素。 To actually center the page, add margin: auto.要真正使页面居中,请添加边距:自动。

The following example will center the website on screens that are wider than 500px.以下示例将网站置于宽度超过 500 像素的屏幕上。 On screens that are less than 500px wide, it will span the whole of the page:在宽度小于 500 像素的屏幕上,它将跨越整个页面:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
  background: #555;
}

.content {
  max-width: 500px;
  margin: auto;
  background: white;
  padding: 10px;
}
</style>
</head>
<body>

<div class="content">
  <h1>This page is horizontally centered on screens that are wider than 500 pixels.</h1>
  <h1>Resize the browser window to see the effect.</h1>
  <p>This page is always centered on screens that are wider than 500px. On screens that are less than 
  500px wide, it will span the whole of the page.</p>
  <p>Content inside this container is centered horizontally.</p>
 </div>

</body>
</html>

The body is already 99px wide and centered horizontally.主体已经是 99px 宽并且水平居中。 However, if you want the background color to appear only at the width, I suggest you use the:before pseudo selector like this:但是,如果您希望背景颜色仅出现在宽度上,我建议您使用:before 伪选择器,如下所示:

 body{ position: relative; width: 99px; margin: 0 auto; height: 100vh; } body:before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color:orange; z-index: -1; }
 <h2>Some content here</h2>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM