圣杯布局和双飞翼布局功能相同,都是为了实现一种两侧宽度固定,中间部分宽度自适应的三栏布局,并且中间部分在DOM结构上优先,以便先行渲染。
圣杯布局
首先我们创建DOM结构如下
<div class="container">
<div class="center"></div>
<div class="left"></div>
<div class="right"></div>
</div>
设置三个部分的底色和高度,设置left宽度为200px,right宽度为150px,并让它们浮动。
.center, .left, .right {
height: 500px;
font-size: 22px;
text-align: center;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
float: left;
}
.center {
background-color: pink;
}
.left {
background-color: #999999;
width: 200px;
}
.right {
background-color: powderblue;
width: 150px;
}
效果如下:
可以看到三个部分都挤在最左侧,为了让center充满屏幕,设置center的宽度为100%
这时两侧的内容被挤到了下方,我们给left和right留出它们的位置
.container {
padding: 0 150px 0 200px;
}
现在我们需要让left爬到上面一层去,使用margin-left属性,设成负值,当负值正好大于等于下盒子宽度时,下盒子跑到上盒子所在行
margin-left: -200px;
left成功上去了!
但我们需要left在最左侧,设置margin-left: -100%,相当于向左移动了一个父元素的距离。
参考:圣杯布局中对left盒子设置负内边距-100%的一点解释
但center的左侧内容被left挡住了,我们将left左移(设置当前元素的左侧与父元素左侧的距离值)
position: relative;
left: -200px;
OK,left成功定位。最后我们设置right样式
margin-right: -150px;
至此,圣杯布局已完成,最终CSS代码如下:
body {
background-color: #cccccc;
}
.container {
padding: 0 150px 0 200px;
}
.center, .left, .right {
height: 400px;
font-size: 22px;
text-align: center;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
float: left;
}
.center {
background-color: pink;
width: 100%;
}
.left {
background-color: #999999;
width: 200px;
margin-left: -100%;
position: relative;
left: -200px;
}
.right {
background-color: powderblue;
width: 150px;
margin-right: -150px;
}
双飞翼布局
双飞翼布局的DOM结构和圣杯布局不同,container内只包含了center部分
<div class="container">
<div class="center"></div>
</div>
<div class="left"></div>
<div class="right"></div>
- 因为container和left、right平级,所以我们需要在它们上面加上
float: left;
让三者在一行上浮动 - 设置container的宽度
width: 100%;
- 设置center的外边距,为left和right留位置
margin: 0 150px 0 200px;
- 设置left上移
margin-left: -100%;
- 设置right上移
margin-left: -150px;
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wingsLayout</title>
<style>
body {
background-color: #cccccc;
}
.container {
float: left;
width: 100%;
}
.center, .left, .right {
height: 400px;
font-size: 22px;
text-align: center;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
}
.center {
background-color: pink;
margin: 0 150px 0 200px;
}
.left {
background-color: #999999;
float: left;
width: 200px;
margin-left: -100%;
}
.right {
background-color: powderblue;
width: 150px;
float: left;
margin-left: -150px;
}
</style>
</head>
<body>
<div class="container">
<div class="center">
This is center
<br/>
auto
</div>
</div>
<div class="left">
This is left
<br/>
200px
</div>
<div class="right">
This is right
<br/>
150px
</div>
</body>
</html>
两种布局的比较
圣杯布局和双飞翼布局都可以实现固比固的一种排列方式,效果是相同的。圣杯布局的DOM结构更加的直观和自然,而双飞翼布局不需要定位,代码相对更加简洁。