昨天在做一个仿造豆瓣首页的练习,突然发现自己不会让页面居中。然后百度了一下

页面左右居中

html

1
2
3
4
5
6
7
8
9
10
11
12
13
<html>
<head>
<title>测试居中</title>
<link rel="stylesheet" type="text/css" href="middle.css" />
</head>
<body>
<div class="main">
<h1>
main
</h1>
</div>
</body>
</html>

css

1
2
3
4
5
6
7
8
.main {
text-align: center;
color:#000;
background-color: brown;
width:300px;
height: 350px;
margin:auto;
}

重点是 margin 属性,若是想让这块区域上面留白20px距离,可以改成
margin:20px auto;

页面上下左右居中

css

1
2
3
4
5
6
7
8
9
10
11
12
13
.main {
text-align: center;
color:#000;
background-color: brown;
width:300px;
height: 350px;
margin:auto;
top:0;
bottom: 0;
left:0;
right:0;
position: absolute;
}

在页面左右居中的基础上添加 top、bottom、left、right 及 position 属性。其中前四个属性大小要保持一致,我喜欢将其设置为0。