方案一、
1、利用定位实现两侧固定中间自适应
- 父盒子设置左右padding值
- 给左右盒子的width设置父盒子的padding值,然后分别定位到padding处
- 中间盒子自适应 如图所示:
html结构如下:
<div class="father">
<div class="left">左</div>
<div class="center"></div>
<div class="right">右</div>
</div>
css代码如下:
.father {
height: 400px;
background-color: pink;
position: relative;
padding: 0 200px;
}
.left,
.right {
width: 200px;
height: 300px;
position: absolute;
top: 0;
/* 调试文字位置,更直观的查看圣杯布局 */
text-align: center;
font-size: 20px;
line-height: 300px;
}
.left {
left: 0;
background-color: brown;
}
.right {
right: 0;
background-color: blueviolet;
}
.center {
background-color: #ccc;
height: 350px;
}
方案二、
2、利用flex布局实现两侧固定中间自适应
- 父盒子设置display:flex
- 左右盒子设置固定宽高
- 给中间盒子设置flex:1; 如图所示:
html结构如下:
<div class="father">
<div class="left">左</div>
<div class="center"></div>
<div class="right">右</div>
</div>
css代码如下:
.father {
height: 400px;
background-color: pink;
display: flex;
}
.left,
.right {
width: 200px;
height: 300px;
/* 调试文字位置,更直观的查看圣杯布局 */
text-align: center;
font-size: 20px;
line-height: 300px;
}
.left {
background-color: greenyellow;
}
.right {
background-color: green;
}
.center {
flex: 1;
background-color: skyblue;
}
方案三、
3、利用bfc块级格式化上下文,实现两侧固定中间自适应
- 左右固定宽高,进行浮动
- 中间 voerflow:hidden; 如图所示:
html结构如下:
<!-- 注意:left和right必须放在center前面 -->
<div class="father">
<div class="left">左</div>
<div class="right">右</div>
<div class="center"></div>
</div>
css代码如下:
.father {
height: 500px;
background-color: pink;
}
.left,
.right {
width: 200px;
height: 400px;
/* 调试文字位置,更直观的查看圣杯布局 */
text-align: center;
font-size: 20px;
line-height: 300px;
}
.left {
float: left;
background-color: rgb(99, 47, 255);
}
.right {
float: right;
background-color: rgb(14, 156, 212);
}
.center {
height: 450px;
background-color: rgb(196, 13, 123);
overflow: hidden;
}