CSS两栏布局

左列定宽,右列自适应

float + margin

这里要注意在 HTML 结构中 id=”right” 不能放在 id=”left” 的上边,就是顺序不能颠倒

1
2
3
4
<div id="parent">
<div id="left">左列定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
#left {
background-color: #f00;
float: left;
width: 100px;
height: 500px;
}
#right {
background-color: #0f0;
height: 500px;
margin-left: 100px; /*大于等于#left的宽度*/
}

float + overflow

优缺点:

  • 优点:代码简单,容易理解,无需关注定宽的宽度,利用bfc达到自适应效果
  • 缺点:浮动脱离文档流,需要手动清除浮动,否则会产生高度塌陷;
1
2
3
4
<div id="parent">
<div id="left">左列定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
#left {
background-color: #f00;
float: left;
width: 100px;
height: 500px;
}
#right {
background-color: #0f0;
height: 500px;
overflow: hidden; /*触发bfc达到自适应*/
}

absolute + relative

这个要注意,parent 的高度会都变成 0,不再包裹子元素,慎用

1
2
3
4
<div id="parent">
<div id="left">左列定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#parent{
position: relative; /*子绝父相*/
}
#left {
position: absolute;
top: 0;
left: 0;
background-color: #f00;
width: 100px;
height: 500px;
}
#right {
position: absolute;
top: 0;
left: 100px; /*值大于等于#left的宽度*/
right: 0;
background-color: #0f0;
height: 500px;
}

flex

推荐这种方法

1
2
3
4
<div id="parent">
<div id="left">左列定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
#parent{
width: 100%;
height: 500px;
display: flex;
}
#left {
width: 100px;
background-color: #f00;
}
#right {
flex: 1; /*均分了父元素剩余空间*/
background-color: #0f0;
}

Grid

1
2
3
4
<div id="parent">
<div id="left">左列定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
#parent {
width: 100%;
height: 500px;
display: grid;
grid-template-columns: 100px auto; /*设定2列就ok了,auto换成1fr也行*/
}
#left {
background-color: #f00;
}
#right {
background-color: #0f0;
}

一列不定,一列自适应

float + overflow

优缺点:

  • 优点:代码简单,容易理解,无需关注宽度,利用bfc达到自适应效果
  • 缺点:浮动脱离文档流,需要手动清除浮动,否则会产生高度塌陷;
1
2
3
4
<div id="parent">
<div id="left">左列不定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
#left {
margin-right: 10px;
float: left; /*只设置浮动,不设宽度*/
height: 500px;
background-color: #f00;
}
#right {
overflow: hidden; /*触发bfc*/
height: 500px;
background-color: #0f0;
}

flex

1
2
3
4
<div id="parent">
<div id="left">左列不定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
#parent{
display: flex;
}
#left { /*不设宽度*/
margin-right: 10px;
height: 500px;
background-color: #f00;
}
#right {
height: 500px;
background-color: #0f0;
flex: 1; /*均分#parent剩余的部分*/
}

Grid

1
2
3
4
<div id="parent">
<div id="left">左列不定宽</div>
<div id="right">右列自适应</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
#parent{
display: grid;
grid-template-columns: auto 1fr; /*auto和1fr换一下顺序就是左列自适应,右列不定宽了*/
}
#left {
margin-right: 10px;
height: 500px;
background-color: #f00;
}
#right {
height: 500px;
background-color: #0f0;
}

参考

各种常见布局实现