浮动布局
大约 2 分钟
浮动布局
浮动布局 是指设置元素的 float
属性,使元素紧贴容器(父元素)的左侧或右侧边界,改变元素在正常文档流中的行为,并会影响紧跟着它的下一个元素。利用浮动来实现的页面布局中最常见的是 圣杯布局 和 双飞翼布局
圣杯布局
圣杯布局是将页面分成了五个部分,分别是:页头、页脚、内容区域中的左侧边栏、内容区域、右侧边栏。圣杯布局主要利用元素的 float
、position
属性,配合 padding
、margin
等属性来调整元素的位置从而得以实现。由于左右侧栏都在一个容器中,加上页头与页脚,整体外形看起来就像圣杯一样,故而被称为圣杯布局
代码示例
<div class="header">header</div>
<div class="main">
<div class="left">left</div>
<div class="content">content</div>
<div class="right">right</div>
</div>
<div class="footer">footer</div>
.header,.footer{
width: 100%;
height: 80px;
background-color: orange;
text-align: center;
line-height: 80px;
}
.footer{
clear: both;
}
.main{
width: initial;
height: 240px;
padding: 0 150px;
text-align: center;
line-height: 240px;
}
.left,.right{
float: left;
width: 150px;
height: 100%;
background-color: skyblue;
position: relative;
margin-left: -150px;
}
.content{
float: left;
width: 100%;
height: 100%;
background-color: yellowgreen;
}
.right{
right: -150px;
}
双飞翼布局
双飞翼布局的实际效果与圣杯布局是一致的,不过它们使用元素的方式不同,双飞翼布局是将左右侧边栏从内容区域中独立出来,然后通过设置内容区域以及左右侧栏的 float
属性与 margin
属性来使元素对齐,由于将左右侧栏从内容区域独立出来,看起来就像两片翅膀,故而被称为双飞翼布局
代码示例
<div class="header">header</div>
<div class="main">
<div class="content">content</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
<div class="footer">footer</div>
.header,
.footer {
width: 100%;
height: 80px;
background-color: orange;
text-align: center;
line-height: 80px;
}
.footer {
clear: both;
}
.main {
float: left;
width: 100%;
height: 240px;
text-align: center;
line-height: 240px;
}
.content {
margin: 0 150px;
height: 100%;
background-color: yellowgreen;
}
.left,
.right {
float: left;
width: 150px;
height: 240px;
background-color: skyblue;
margin-left: -150px;
text-align: center;
line-height: 240px;
}
.left {
margin-left: -100%;
}
以上两种布局方式的实现方法略有差异,但都有以下特点:
- 两侧边栏宽度固定,中间内容区域宽度自适应
- 中间内容区域在DOM结构上优先,以便先行渲染
- 允许三列中的任意一列高度最高
ℹ️提示
圣杯布局与双飞翼布局本质上是三栏水平布局,它们还有许多其他的实现方法,这里只展示了利用浮动来实现的方式