Xu•thus Blog

CSS布局之三栏布局

三栏布局是一种使用非常广泛的布局方式,一般是左右固定宽度,中间内容自适应

这里收集了三栏布局的五种方法

浮动布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.left {
width: 200px;
background: red;
float: left;
height: 100px;
}
.right {
width: 200px;
background: yellow;
float: right;
height: 100px;
}
.center {
background: blue;
height: 100px;
}
</style>
</head>
<body>
<div class="box">
<div class="left"></div>
<div class="right"></div>
<div class="center"></div>
</div>
</body>
</html>

优点:兼容性好,易上手
缺点:浮动会脱离文档流,需要清除浮动

绝对定位

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box > div {
position: absolute;
height: 100px;
}
.left {
width: 200px;
left: 0;
background: red;
}
.right {
width: 200px;
right: 0;
background: yellow;
}
.center {
left: 200px;
right: 200px;
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>

优点:简单,快速
缺点:会脱离文档流

flexbox布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
display: flex;
width: 100%;
}
.box > div {
height: 100px;
}
.left {
width: 200px;
background: red;
}
.right {
width: 200px;
background: yellow;
}
.center {
flex: 1;
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
</html>

优点:快速,未来趋势

表格布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
width: 100%;
display: table;
}
.box > div {
height: 100px;
display: table-cell;
}
.left {
width: 200px;
background: red;
}
.right {
width: 200px;
background: yellow;
}
.center {
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
</html>

优点:兼容性好
缺点:对复杂页面来说,操作繁琐,seo不友好

网格布局

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.box {
width: 100%;
display: grid;
grid-template-rows: 100px;
grid-template-columns: 200px auto 200px;
}
.left {
background: red;
}
.right {
background: yellow;
}
.center {
background: blue;
}
</style>
</head>
<body>
<div class="box">
<div class="left"></div>
<div class="center"></div>
<div class="right"></div>
</div>
</body>
</html>

优点:新技术,快速
缺点:兼容性问题