Contents
  1. 1. 左边固定,右边自适应的双栏布局的几种实现方式
    1. 1.1. 一、双inline-block
    2. 1.2. 二、双float
    3. 1.3. 三、float+margin-left
    4. 1.4. 四、absolute+margin-left
    5. 1.5. 五、float+BFC
    6. 1.6. 六、flex方法
    7. 1.7. 七、grid

左边固定,右边自适应的双栏布局的几种实现方式

总结一下最近看的一个博客,一共有七种方法

一、双inline-block

1
2
3
4
5
6
7
8
9
10
11
.left {
width: 140px;
}
.left, .right {
display: inline-block;
vertical-align: top;
box-sizing: border-box;
}
.right {
width: calc(100%-140px);
}

这个是用calc来计算右边盒子的宽度,要知道左边的呢宽度是多少,父盒子设置font-size为0可以消除空格字符的影响,要设置vertical-align

要注意calc的兼容以及用法 运算符号前后要有空格记得。

二、双float

这个也是一直自己用的方法

1
2
3
4
5
6
7
8
9
10
11
12
.wrapper {
overflow: auto;
}
.left, .right {
box-sizing: border-box;
float: left;
height: 200px;
}
.right {
background-color: #00ff00;
width: calc( 100% - 140px );
}

也是用calc来设置右边的宽度,这个要注意清除浮动,自己写的时候用的宽度方法是用百分比来控制,之后可以考虑calc,不过也要根据实际项目需求

三、float+margin-left

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.wrapper {
overflow: hidden;
}
.left {
width: 140px;
background-color: #ff0000;
float: left;
height: 200px;
}
.right {
height: 200px;
background-color: #00ff00;
margin-left: 140px;
}

根据块级盒子具有填满父容器,并且随着父容器的宽度进行自适应的流动特征来实现的这个方案,右边盒子的margin-left是左边宽度加上离左边的距离。要注意清除浮动。之后的可能可以考虑这个方案

四、absolute+margin-left

1
2
3
4
5
6
7
8
9
10
11
.left {
width: 140px;
background-color: #ff0000;
height: 200px;
position: absolute;
}
.right {
height: 200px;
background-color: #00ff00;
margin-left: 140px;
}

用了绝对定位 没有清除浮动 如果左边高于右边会超过父元素,要设置父元素的min-height 这个方案以前没有接触过,有点疑问,等之后闲下来可以看看

五、float+BFC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.wrapper {
overflow: auto;
}
.left {
width: 140px;
background-color: #ff0000;
height: 200px;
float: left;
margin-right: 20px;
}
.right {
height: 200px;
background-color: #00ff00;
margin-left: 0;
overflow: auto;
}

这个是左边设置margin-right来实现两个盒子的距离,右边的overflow:auto来形成BFC 父元素要清除浮动

六、flex方法

这个兼容有问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
.wrapper {
display: flex;
align-items: flex-start;
}
.left {
width: 140px;
background-color: #ff0000;
height: 200px;
flex: 0 0 auto;
}
.right {
height: 200px;
background-color: #00ff00;
flex: 1 1 auto;
}

七、grid

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.wrapper {
display: grid;
grid-template-columns: 120px 1fr;
align-items: start;
}
.left, .right {
box-sizing: border-box;
}
.left {
width: 140px;
background-color: #ff0000;
height: 200px;
grid-column: 1;
}
.right {
height: 200px;
background-color: #00ff00;
grid-column: 2;
}
Contents
  1. 1. 左边固定,右边自适应的双栏布局的几种实现方式
    1. 1.1. 一、双inline-block
    2. 1.2. 二、双float
    3. 1.3. 三、float+margin-left
    4. 1.4. 四、absolute+margin-left
    5. 1.5. 五、float+BFC
    6. 1.6. 六、flex方法
    7. 1.7. 七、grid