前提知识:
margin属性:
margin:25px 50px 75px 100px;
顺序为顺时针:上右下左margin:0 auto;
表示上下外边距为0,左右外边距由浏览器平均分配,如果指定块级元素宽度,则会实现水平对齐。
单列布局1
将全屏平均分成上中下三部分,宽度为浏览器窗口宽度。
效果:
代码:
- html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="单列布局3.css">
</head>
<body>
<div id="header">头部</div>
<div id="content">内容</div>
<div id="footer">尾部</div>
</body>
</html>
- css部分
/*最普通的单列布局*/
*{
margin: 0;
}
#header {
background-color: #eedd44;
color: red;
}
#content {
background-color: #279065;
color: #000;
}
#footer {
background-color: #cc675d;
color: #aaa;
}
#header,#content,#footer {
text-align: center;
}
单列布局2
限定最大宽度,超过最大宽度时自适应显示,水平居中
效果图:
代码:
- html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="单列布局1.css">
</head>
<body>
<div class="layout">
<div id="header">头部</div>
<div id="content">内容</div>
<div id="footer">底部</div>
</div>
</body>
</html>
- css部分
/*header、content、footer宽度都相同,
其不会占满浏览器的最宽宽度,
但当浏览器宽度缩小低于其最大宽度时,宽度会自适应。*/
.layout {
max-width: 960px;
margin: 0 auto;/*上下边距为0,左右边距为auto*/
/*上右下左顺时针*/
}
#header {
background-color: #eedd44;
color: red;
}
#content {
background-color: #000;
color: #638839;
}
#footer {
background-color: #cc675d;
color: #aaa;
}
#header,#content,#footer {
text-align: center;
}
单列布局3
头部和底部为占满浏览器窗口,内容限定宽度并居中
效果图:
代码:
- html部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="单列布局2.css">
</head>
<body>
<div id="header">
<div class="layout">头部</div>
</div>
<div id="content" class="layout">内容</div>
<div id="footer">
<div class="layout">尾部</div>
</div>
</body>
</html>
- css部分
/*header、footer宽度为浏览器宽度,
但content以及header和footer里的内容
却不会占满浏览器宽度。*/
.layout{
max-width: 960px;
margin: 0 auto;
}
#header {
background-color: #eedd44;
color: red;
}
#content {
background-color: #279065;
color: #000;
}
#footer {
background-color: #cc675d;
color: #aaa;
}
#header,#content,#footer {
text-align: center;
}
总结
因为div默认宽度为浏览器宽度,如果不设定宽度利用margin属性设置水平居中就会多此一举,所以利用margin属性水平居中一定需要盒子设定宽度。
既然通过margin:0 auto;
可以设置水平居中,那么可不可以通过margin:auto 0;
设置垂直居中呢?
显然不行,因为浏览器可以向下滚动,其高度不固定,不像宽度可以自适应。