三欄式布局
三欄式布局就是兩邊固定,中間自适應。
三欄式布局實作方法有很多,包括:
- 流體布局
- BFC三欄布局
- 雙飛翼布局
- 聖杯布局
- Flex布局
- Table布局
- 絕對定位布局
- 網格布局
流體布局
左側向左浮動、右側向右浮動,最後渲染中間實作;最後渲染中間也就意味着在html中内容div寫在最後,并設定中間子產品的 margin 值使中間子產品寬度自适應
缺點就是主要内容無法最先加載,當頁面内容較多時會影響使用者體驗
<div class="wrap">
<div class="left">左側</div>
<div class="right">右側</div>
<div class="main">中間</div>
</div>
<style>
*{
margin: 0;
border: 0;
}
.left{
width: 100px;
height:500px;
background-color: yellow;
float: left;
}
.right{
width: 200px;
height: 500px;
background-color: palevioletred;
float: right;
}
.main{
height: 500px;
background-color: aqua;
margin-left: -100px;
margin-right: -200px;
}
</style>
效果:

BFC布局
BFC 區域,不會與浮動元素重疊。左右子產品各自向左右浮動,并設定中間子產品的 overflow:hidden
,使中間子產品寬度自适應
<style>
*{
margin: 0;
border: 0;
}
.left{
width: 100px;
height:500px;
background-color: yellow;
float: left;
}
.main{
height: 500px;
background-color: aqua;
overflow: hidden;
}
.right{
width: 200px;
height: 500px;
background-color: palevioletred;
float: right;
}
</style>
雙飛翼布局
按照“中左右”的順序排放元素,都設定浮動,最中間元素寬度設定為100%,
利用左右margin負邊距将左右元素拉到左右位置
利用的是浮動元素和 margin 負值(中間設定子元素,margin的左右值是左右兩邊元素的寬度),主體内容可以優先加載,HTML 代碼結構稍微複雜點。
<div class="wrap">
<div class="center">
<div class="center-child">中間mmmmmmmmmm</div>
</div>
<div class="left">左側</div>
<div class="right">右側</div>
</div>
<style>
.wrap{
border: 1px solid #000;
overflow: hidden;
}
.center{
width:100%;
height:500px;
background-color: yellow;
float: left;
}
.center-child{
width:100%;
height: 400px;
background-color: aqua;
//為子元素設定左右margin,防止内容被遮擋
margin-left: 150px;
margin-right: 250px;
}
.left{
width:150px;
height:500px;
background-color: red;
float: left;
margin-left: -100%;
}
.right{
width:250px;
height:500px;
background-color: blue;
float: left;
margin-left:-250px;
}
</style>
效果:
聖杯布局
按照“中左右”的順序排放元素,都設定浮動,最中間元素寬度設定為100%,
利用左右margin負邊距将左右元素拉到左右位置
聖杯布局使用padding和定位(父元素設定左右padding,再給左右元素設定相對定位)
<div class="wrap">
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
<style>
.wrap{
border:1px red solid;
padding:0 250px 0 200px;
}
.wrap>div{
float: left;
height:300px;
}
.wrap:after{
display:block;
content: "";
clear:both;
}
.center{
width:100%;
background-color:yellow;
}
.left{
width:200px;
background-color:blue;
margin-left:-100%;
position:relative;
left:-200px;
}
.right{
width:250px;
background-color:green;
margin-left:-250px;
position:relative;
right:-250px;
}
</style>
效果:
Flex布局
給父元素設定
display: flex;justify-content: space-around
即可,代碼簡單友善
<div class="wrap">
<div class="left">左側</div>
<div class="center">中間</div>
<div class="right">右側</div>
</div>
<style>
.wrap{
display: flex;
justify-content: space-around;
}
.left{
width:200px;
height:500px;
background-color: blue;
}
.center{
width:100%;
height:500px;
background-color: yellow;
}
.right{
width:100px;
height:500px;
background-color: pink;
}
</style>
效果:
最後,要注意區分聖杯布局和雙飛翼布局哦1