前言
圣杯布局和双飞翼布局解决的问题是一样的,就是两边定宽,中间自适应的三栏布局(中间栏放在文档流前面优先渲染!)
区别
圣杯布局和双飞翼布局解决问题的方案在前一半是相同的:
也就是三栏全部浮动,但左右两栏加上负margin让其跟中间栏div并排。
不同在于解决 “中间栏div内容不被遮挡” 问题的思路不一样。
圣杯布局

image.png
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8" />
<style>
.container {
padding: 0 100px 0 200px;
}
.left {
width: 200px;
background: red;
/* 关键点:会让元素沿文档流向左移动,负数值比较大的话会一直移动到上一行 */
margin-left: -100%;
left: -200px;
}
.right {
width: 100px;
background: blue;
margin-left: -100px;
right: -100px;
}
.main {
background: yellow;
width: 100%;
}
.left, .main, .right{
float: left;
min-height: 200px;
position: relative;
}
</style>
</head>
<body>
<div class="container">
<div class="main">main</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
双飞翼布局
中间的 div 外层用另一个 div 📦包裹了一下,然后利用 margin 来把嵌套的 div “挤”到中间
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>实现三栏水平布局之双飞翼布局</title>
<style type="text/css">
.left, .main, .right {
float: left;
min-height: 130px;
text-align: center;
}
.left {
margin-left: -100%;
background: green;
width: 200px;
}
.right {
margin-left: -300px;
background-color: red;
width: 300px;
}
.main {
background-color: blue;
width: 100%;
}
.content{
/* 关键点:用margin把div挤到中间正常展示*/
margin: 0 300px 0 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="main">
<div class="content">main</div>
</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
ps:其实还有其它方法解决 “中间栏div内容不被遮挡” 问题,见下面关键点2!!!
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8" />
<style>
.container {
padding: 0 100px 0 200px;
}
.left {
width: 200px;
background: red;
/* 关键点:会让元素沿文档流向左移动,负数值比较大的话会一直移动到上一行 */
margin-left: -100%;
left: -200px;
}
.right {
width: 100px;
background: blue;
margin-left: -100px;
right: -100px;
}
.main {
background: yellow;
width: 100%;
/* 关键点2!!! */
box-sizing: border-box;
padding: 0 100px 0 200px;
}
.left, .main, .right{
float: left;
min-height: 200px;
position: relative;
}
</style>
</head>
<body>
<div class="container">
<div class="main">main</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
Flex布局
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>实现三栏水平布局之Flex布局</title>
<style type="text/css">
.container{
display: flex;
min-height: 130px;
}
.main{
flex-grow: 1;
background-color: blue;
}
.left{
order: -1;
flex-basis: 200px;
background-color: green;
}
.right{
flex-basis: 300px;
background-color: red;
}
</style>
</head>
<body>
<div class="container">
<div class="main">main</div>
<div class="left">left</div>
<div class="right">right</div>
</div>
</body>
</html>
关键点:左右定宽用 flex-basis!!!