一、圣杯布局与双飞翼布局区别
如果将布局结构拆分成容器、左固定、中适应、右固定四部分,在圣杯布局中,左固定、中适应和右固定三部分都位于容器中;而在双飞翼布局中,只有中适应位于容器中,左固定和右固定两部分位于容器外。
在代码中结构如下:
圣杯布局
<div class="container">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
//CSS基本样式(每种方法都具备)
.container{
height: 400px;
background-color: #F0F8FF;
}
.left, .right{
width: 100px;
height: 50px;
background-color: #FAEBD7;
}
.center{
height: 50px;
background-color: aqua;
}
双飞翼布局
<div class="container">
<div class="center"></div>
</div>
<div class="left"></div>
<div class="right"></div>
二、圣杯布局实现
方法一:float+margin
将容器左右padding值设为和左右固定的width相同的值,左固定、右固定和中适应向左浮动,并且通过将margin-left和margin-right设为负的宽度值,使其左固定和右固定贴近容器的两边。
.container{
height: 400px;
padding: 0 100px;
background-color: #F0F8FF;
}
.left, .right{
float: left;
width: 100px;
height: 100px;
background-color: #FAEBD7;
}
.left{
margin-left: -100px;
}
.right{
margin-right: -100px;
}
.center{
width: 100%;
height: 100px;
float: left;
background-color: aqua;
}
方法二:float+calc
左固定、中适应和右固定都向左浮动,中适应的宽度设为 calc(100% - 200px)
.left, .center, .right{
float: left;
}
.center{
width: calc(100% - 200px);
}
方法三:flex布局
.container{
display: flex;
}
.center{
flex-grow: 1;
/* width: 100%;也可以 */
}
方法四:绝对定位
.container{
position: relative;
}
.left{
position: absolute;
left: 0;
}
.right{
position: absolute;
top: 0;
right: 0;
}
.center{
margin: 0 100px;
}
二、双飞翼布局实现
方法一:float
容器,左固定,右固定都向左浮动,容器宽度设为100%,中适应的左右margin设为左右固定的宽度,左固定margin-left:-100%;右固定margin-left设为负的右固定width。
.container{
float: left;
width: 100%;
height: 100px;
background-color: #F0F8FF;
}
.center{
height: 100px;
margin: 0 100px;
background-color: #FAEBD7;
}
.left, .right{
float: left;
width: 100px;
height: 100px;
background-color: #00FFFF;
}
.left{
margin-left: -100%;
}
.right{
margin-left: -100px;
}