如何使用HTML/CSS使页面布局居中?

3

我刚开始学习HTML和CSS并尝试从头开始创建一个非常基础的网页布局。

我希望将页面上的所有元素(导航栏、页眉、内容区、页脚等)居中,同时保留左侧的导航栏。我已经设置好了页面本身,但是无法弄清楚如何进行居中设置。目前我正在使用float:left,所以我想这可能是我的问题,但是我不知道如何使布局正常。

以下是代码:

header {
 text-align: center;
 width: 960px;
}

nav {
 line-height: 30px;
 float: left;
 padding: 5px;
 height: 100px;
 width: 200px;
}

section {
 float: left;
 padding: 5px;
 width: 800px;
}

footer {
 background-color: gray;
 text-align: center;
 padding: 5px;
 width: 960px;
 clear: both;
}
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Test HTML Page</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <header>
  <h1>Heading</h1>
 </header>
 <nav>
  <ul>
   <li><a href="#">Page 1</a></li>
   <li><a href="#">Page 2</a></li>
   <li><a href="#">Page 3</a></li>
  </ul>
 </nav>
 <section>
  <h2>Heading</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec est nunc, iaculis in mauris vitae, commodo ullamcorper lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas posuere in libero id dictum. Phasellus viverra rutrum mollis.</p>
 </section>
 <footer>
  Copyright 2016
 </footer>
</body>
</html>

感谢您的任何帮助!
3个回答

3
您需要在 body 上设置宽度,并使用 margin: 0 auto 居中。这将把上下边距设置为0,并自动调整左右边距,使页面居中。
body {
  width: 960px;
  margin: 0 auto;
}

仅仅因为body的宽度(现在是960px)比你的

太棒了!非常感谢您提供的信息性回复。 :D - StarDart

2
body {margin: 0 auto}
nav {float: left}
选择器会使所有内容居中,由于导航栏选择器比选择器更加具体,因此导航栏将向左对齐。

2
如果您想让它居中,最好将所有材料放在一个
中:
<body>
<div class="wrapper">
    <header>
        <h1>Heading</h1>
    </header>
    <nav>
        <ul>
            <li><a href="#">Page 1</a></li>
            <li><a href="#">Page 2</a></li>
            <li><a href="#">Page 3</a></li>
        </ul>
    </nav>
    <section>
        <h2>Heading</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec est nunc, iaculis in mauris vitae, commodo ullamcorper lacus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas posuere in libero id dictum. Phasellus viverra rutrum mollis.</p>
    </section>
    <footer>
        Copyright 2016
    </footer>
</div>
</body>

还有在你的CSS中:

.wrapper{
   width: 800px;
   margin: 0 auto;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接