css 实现左右左边固定,右边自适应的布局

这是一个比较古老的面试题,面试css的时候会问能有多少种方案来实现,没有标准答案,答案越多越好,主要是考查对css基础布局的理解和掌握情况

页面如下结构:

1
2
3
4
5
<!-- GLOBAL Html -->
<div class="box">
<div class="left">200px</div>
<div class="right">自适应</div>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* GLOBAL css */
.xxSection {
padding: 0;
}
.box {
position: relative;
height: 100vh;
background: #efefef;
}

.left {
width: 200px;
background: #409EFF;
height: 100%;
}
.right {
background: #42b983;
height: 100%;
}

float + margin / absolute + margin

这种方法在老版本浏览器时代比较常用,兼容性好

1
2
3
4
5
6
7
.left {
float: left;
}

.right {
margin-left: 200px;
}

这种方式左边脱离文档流,右边利用了marginLeft 来偏移一个元素实现自适应,左边使用绝对定位也是同样的效果

1
2
3
4
5
6
7
.left {
position: absolute;
}

.right {
margin-left: 200px;
}

绝对定位 + padding

利用父容器一个padding left的值

1
2
3
4
5
6
7
.box {
padding-left: 200px;
}
.left {
left: 0;
position: absolute;
}

table

使用table 布局

1
2
3
4
5
6
7
.box {
width: 100%;
display: table;
}
.box>div{
display: table-cell;
}

flex

css3 flex

1
2
3
4
5
6
.box {
display: flex;
}
.right {
flex:1
}

css计算属性

css计算属性 可以配合各种布局,实际就是固定了左右的宽度

1
2
3
4
5
6
.right {
position: absolute;
width: calc(100% - 200px);
right: 0;
top: 0;
}