常见的自适应布局又以下两种:
1.左列固定右列自适应
说明:左列固定右列自适应,也可以右列固定左列自适应
<div class="container">
<div class="left">固定宽度</div>
<div class="right">自适应</div>
</div>
实现:
方式1:子元素float:left
思路:左列固定列设置为float:left(设置固定宽度),右列自适应设置为float:none(宽度100%)
* { margin: 0;padding: 0 }
.container {
position: absolute;
width: 100%;
height: 100%;
}
.left {
float: left;
width: 200px;
height: 100%;
background-color: #72e4a0;
}
.right {
float: none;
width: 100%;
height: 100%;
background-color: #9dc3e6;
}
方式2 子元素 width:calc()
思路:
自适应列的width根据calc()自动计算,如:父容器width - 固定列width
这个固定宽是你设置的其中一列的w
* { margin: 0;padding: 0 }
.container {
position: absolute;
width: 100%;
height: 100%;
}
.left {
float: left;
width: 200px;
height: 100%;
background-color: #72e4a0;
}
.right {
float: left;
width: calc(100% - 200px);
height: 100%;
background-color: #9dc3e6;
}
方式3 父元素display:flex
* { margin: 0;padding: 0 }
.container {
position: absolute;
display: flex;
width: 100%;
height: 100%;
}
.left {
width: 200px;
height: 100%;
background-color: #72e4a0;
}
.right {
flex: 1;
height: 100%;
background-color: #9dc3e6;
}
2.左右两列固定,中间自适应
<div class="container">
<div class="left">左侧定宽</div>
<div class="mid">中间自适应</div>
<div class="right">右侧定宽</div>
</div>
方式1 子元素float:left
思路:
自适应列的width根据calc()自动计算,如:父容器width - 固定列width。
* { margin: 0;padding: 0 }
.container {
position: absolute;
width: 100%;
height: 100%;
}
.left {
float: left;
width: 100px;
height: 100%;
background-color: #72e4a0;
}
.mid {
float: left;
width: calc(100% - 100px - 100px);
height: 100%;
background-color: #9dc3e6;
}
.right {
float: left;
width: 100px;
height: 100%;
background-color: #4eb3b9;
}
方式2 父元素display:flex
思路:
在父元素设置display为flex时,其中一列的flex为1,其余列都设置固定width。
* { margin: 0;padding: 0 }
.container {
position: absolute;
display: flex;
width: 100%;
height: 100%;
}
.left {
float: left;
width: 100px;
height: 100%;
background-color: #72e4a0;
}
.mid {
float: left;
height: 100%;
flex: 1;
background-color: #9dc3e6;
}
.right {
float: left;
width: 100px;
height: 100%;
background-color: #4eb3b9;
}