網頁實質是塊與塊之間的位置,塊挨着塊,塊嵌套塊,塊疊着塊。
三種關系:相鄰,嵌套,重疊。
下面介紹網頁布局的常用幾種方式

1.一列布局:
一般都是固定的寬高,設置margin : 0 auto來水平居中,用於界面顯著標題的展示等;
.main{
width: 200px;
height: 100px;
background-color: grey;
margin: 0 auto;
}
<div class="main"></div>
2.兩列布局:
說起兩列布局,最常見的就是使用float來實現。float浮動布局的缺點是浮動后會造成文本環繞等效果,以及需要及時清除浮動。
設置左左浮動,或設置左右浮動(這是需要確定父級元素的寬度)
如何父級元素沒有設置高度,則需要設置overflow:hidden來清除浮動產生的影響
對於自己相鄰元素清除浮動產生的影響用:clear:both;

<div class="main">
<div class="left">left</div>
<div class="right">right</div>
</div>
.main{
width: 400px;
background: red;
overflow: hidden;
}
.left{
background: yellow;
float: left;
}
.right{
background: green;
float: left;
}
3.三列布局:
兩側定寬中間自適應
首先設置父級元素的寬度,可以左左右設置浮動。然后中間設置margin調整間距。 也可以都設置成左浮動,設置margin,調整間距。同樣注意清除浮動的影響!
![]()
<div class="main">
<div class="left">left</div>
<div class="middle">middle</div>
<div class="right">right</div>
</div>
.main{
width: 100%;
background: red;
overflow: hidden;
}
.left{
background: yellow;
float: left;
width: 100px;
}
.middle{
background: rosybrown;
float: left;
width: cacl(100%-200px);
}
.right{
background: green;
float: right;
width: 100px%;
}
或着為父級元素設置relative屬性,再為子元素設置absolute屬性,再分別定位,調間距。

<div class="parent" style="">
<div class="left" style="">
<p>left</p>
</div>
<div class="center" style="">
<p>center</p>
<p>center</p>
</div>
<div class="right" style="">
<p>right</p>
</div>
</div>
<style>
p{margin: 0;}
.parent{position: relative;height:40px;}
.left,.right,.center{position: absolute;}
.left{left: 0;width:100px;}
.right{right: 0;width: 100px;}
.center{left: 120px; right: 120px;}
</style>
4.混合布局:
在一列布局的基礎上,保留top和foot部分,將中間的main部分改造成兩列或三列布局,小的模塊可以再逐級同理划分。

<div class="top"></div>
<div class="main">
<div class="left">left</div>
<div class="right">right</div>
</div>
<div class="footer"></div>
.top{
height: 100px;
background: teal;
}
.footer{
height: 100px;
background: wheat;
}
.main{
width: 100%;
background: red;
overflow: hidden;
}
.left{
background: yellow;
float: left;
width: 50%;
}
.right{
background: green;
float: right;
width: 50%;
}
5.擴展(如等分布局等)

<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
body{margin: 0;}
.parent{
border: 1px solid red;
overflow: hidden;
margin-right: -10px;
}
.child {
width: calc(25% - 10px);
height: 100px;
background: green;
float: left;
margin-right: 10px;
}

