「这是我参与2022首次更文挑战的第7天,活动详情查看:2022首次更文挑战」。
在开发中我们经常被要求写出两边固定,中间自适应的样式,实现的方法有如下几种
一、使用flex布局
父元素设置display:flex,两侧子元素设置宽高,中间子元素设置flex:1
//html代码
<div class="father">
<div class="left">左侧</div>
<div class="center">中间</div>
<div class="right">右侧</div>
</div>
//css代码
.father {
display: flex;
}
.left,
.right {
width: 100px;
height: 100px;
background-color: red;
}
.center{
flex: 1;
background-color: yellow;
}
效果图:
二、使用float浮动
两侧子元素分别设置左右浮动,中间自适应元素必须放在两侧元素后面,因为中间元素会占据文档流位置。
//html代码
<div class="father">
<div class="left">左浮动</div>
<div class="right">右浮动</div>
<div class="center">中间</div>
</div>
//css代码
.left,.right {
width: 100px;
height: 100px;
background-color:red;
}
.left{
float: left;
}
.right{
float:right;
}
.center{
background-color: yellow;
height: 100px;
}
效果图:
三、利用绝对定位
利用两侧元素绝对定位设置宽高,中间自适应元素放在两侧元素后面,并且设置左右间隔。
//html代码
<div class="father">
<div class="left">绝对定位</div>
<div class="right">绝对定位</div>
<div class="center">设置左右margin间隔</div>
</div>
//css代码
*{
margin: 0;
padding: 0;
}
.left,
.right {
position: absolute;
width: 100px;
height: 100px;
background-color: red;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
height: 100px;
margin-left: 100px;
margin-right: 100px;
background-color: yellow;
}
效果图:
四、利用calc计算中间宽度
三个元素都设置一个方向的浮动,中间宽度由总体宽度减去两侧宽度计算得出
//html代码
<div class="father">
<div class="left">左浮动</div>
<div class="center">中间自适应</div>
<div class="right">左浮动</div>
</div>
//css代码
.left,.right,.center{
float: left;
background-color: red;
width: 100px;
height: 100px;
}
.center{
background-color: yellow;
width: calc(100% - 100px - 100px);
}
效果图:
五、圣杯布局
圣杯布局是前端面试中最常被问到的一种布局。 要求:三列布局,中间主体内容前置且宽度自适应,两边内容定宽。 好处:重要的内容放在文档前面可以优先渲染 实现:通过浮动,相对定位,负边距布局。
具体实现
- 父元素包含三个子元素,都设置左浮动
- 中间元素的宽度设置为100%,并在三个元素的第一个
- 左右两边使用margin-left的负值,左边元素为-100%,右边元素为-自身元素大小
- 父元素通过padding设置左右两边留白
- 左右两侧设置position:relative,利用left移动位置
//html代码
<div class="father">
<div class="center"></div>
<div class="left">左侧</div>
<div class="right">右侧</div>
</div>
//css代码
.father {
padding-left: 150px;
padding-right: 190px;
height: 100px;
} //父元素设置内边框
.center {
float: left;
width: 100%;
height: 100px;
background-color: yellow;
} //中间自定义元素设置左浮动
.left {
float: left;
position: relative;
margin-left: -100%;
left: -100px;
width: 100px;
height: 100px;
background-color: red;
} //左边元素设置固定宽度,相对定位布局
.right {
float: left;
position: relative;
right: -100px;
margin-left: -100px;
width: 100px;
height: 100px;
background-color: red;
} //右边同
六、双飞翼布局
对圣杯相对定位的改进,消除相对定位 原理:主体元素使用左右边距,预留两侧位置。左右两栏使用浮动和负边距归位。
在这里插入代码片