基本理解
圣杯布局与双飞翼布局针对的都是三列左右栏固定中间栏边框自适应的网页布局,圣杯布局是Kevin Cornell在2006年提出的一个布局模型概念,在国内最早是由淘宝UED的工程师(传说是玉伯)改进并传播开来,在中国也有叫法是双飞翼布局,它的布局要求有几点:
三列布局,中间宽度自适应,两边定宽;
中间栏要在浏览器中优先展示渲染;
允许任意列的高度最高;
语义化解释
所谓的圣杯布局就是左右两边大小固定不变,中间宽度自适应。一般这种布局方式适用于各种移动端顶部搜索部分。
方法一
利用定位实现两侧固定中间自适应
1.1)父盒子设置左右 padding 值
1.2)给左右盒子的 width 设置父盒子的 padding 值,然后分别定位到 padding 处.
1.3)中间盒子自适应
具体 CSS 代码:
<style>
.father {
height: 400px;
background-color: pink;
position: relative;
padding: 0 200px;
}
.left,.right {
width: 200px;
height: 300px;
background-color: yellow;
position: absolute;
top: 0;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
background-color: blue;
height: 350px;
}
</style>
html 结构
<div class="father">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
方法二
利用 flex 布局实现两侧固定中间自适应
2.1)父盒子设置 display:flex;
2.2)左右盒子设置固定宽高
2.3)中间盒子设置 flex:1 ;
.father {
height: 400px;
background-color: pink;
display: flex;
}
.left {
width: 200px;
height: 300px;
background-color: yellow;
}
.right {
width: 200px;
height: 300px;
background-color: yellow;
}
.center {
flex: 1;
background-color: blue;
}
</style>
html 结构
<div class="father">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
方法三
利用 bfc 块级格式化上下文, 实现两侧固定中间自适应
3.1)左右固定宽高,进行浮动
3.2)中间 overflow: hidden;
.father {
height: 500px;
background-color: pink;
}
.left {
float: left;
width: 200px;
height: 400px;
background-color: blue;
}
.right {
float: right;
width: 200px;
height: 400px;
background-color: blue;
}
.center {
height: 450px;
background-color: green;
overflow: hidden;
}
</style>
html 结构
<!-- 注意:left 和 right 必须放在 center 前面 -->
<div class="father">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>