本篇主要记录的网页布局方式有:一列布局,两列布局,三列布局,以及混合布局。
1.一列布局
【水平居中】
为块状元素设置样式: margin:0 auto;
。
(若是为行内元素或其他设置水平居中,见HTML学习(V))
2.两列布局
【左右】
通过为两块元素设置左右浮动
(1)自适应宽度的两列布局
*{margin: 0; padding: 0; }
.left{width: 20%; height: 500px; background: #fff; float: left; }
.right{width: 80%; height: 500px; background: #ccc; float: right; }
(2)固定宽度的两列布局
<head>
<meta …… />
<title>**</title>
<style type="text/css">
body{ margin:0; padding:0; font-size:30px; font-weight:bold}
div{ text-align:center; line-height:50px}/*让子元素(文字)在父元素(div)中水平居中显示*/
.main{ width:960px; height:600px; margin:0 auto}
.left{ width:300px; height:600px; background:#ccc; float:left;}
.right{ width:390px; height:600px; background:#FCC; float:right;}/*left和right的宽度相加之和可以小于等于父元素的宽度*/
</style>
</head>
<body>
<div class="main">
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
3.三列布局
【左中右】
(浮动模型见HTML学习(IV))
(1)自适应宽度的三列布局
*{margin: 0; padding: 0; }
.left{width: 33.33%; height: 700px; background: #bbb; float: left; }
.middle{width: 33.33%; height: 700px; background: #abc; float: left;}
.right{width: 33.33%; height: 700px; background: #afe; float: right;}
(2)固定宽度的三列布局
【使用绝对定位的方法,而不是浮动】
左右固定,中间的部分自适应。
.left{ width:200px; height:600px; position:absolute; left:0; top:0; background:#CCC;}
.main{ height:600px; margin:0 310px 0 210px; background:#9CF;}
.right{ width:300px; height:600px; position:absolute; right:0; top:0; background:#FCC;}
4.混合布局
<style>
body{ margin:0; padding:0; font-size:30px; font-weight:bold}
div{ text-align:center; line-height:50px}
.top{ height:100px;background:#9CF}
.head,.main{ width:960px; margin:0 auto;}
.head{ height:100px; background:#F90}
.left{ width:220px; height:600px; background:#ccc; float :left;}
.right{ width:720px; height:600px;background:#FCC; float:right;}/*将主体main分为两列left和right*/
.r_sub_left{ width:520px; height:600px; background:#9C3; float:left}
.r_sub_right{ width:180px; height:600px; background:#9FC; float:right;}/*将right分为两列r_sub_left和r_sub_right*/
.footer{ width:100%; height:50px; background:#9F9; overflow:hidden;}
</style>