三栏布局的五种实现方法

Web页面布局

要求:三栏布局左右各300像素,中间自适应

HTML结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
html,body{ margin: 0; width: 100%; }
/* other style */
</style>
</head>
<body>
<div class="container">
<div class="left">left</div>
<div class="center">center</div>
<div class="right">right</div>
</div>
</body>
</html>

一、浮动

1
2
3
4
.container{ overflow: hidden; }
.left{ width: 300px; float: left; background-color: red; padding-bottom: 10000px; margin-bottom: -10000px;}
.right{ width: 300px; float: right; background-color: blue; }
.center{ background-color: yellow; margin: 0 310px;}

上面的HTML结构要调整下

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
/* ... */
</head>
<body>
<div class="container">
<div class="left">left</div>
<div class="right">right</div> <!-- 让右栏先浮上去 -->
<div class="center">center</div>
</div>
</body>
</html>

使用

1
2
.container{ overflow: hidden; }
.left{ padding-bottom: 10000px; margin-bottom: -10000px;}

实现左边栏始终随center部分撑满页面

二、绝对定位

1
2
3
4
.container{ position: relative; }
.left{ width: 300px; position: absolute; left: 0; top: 0; background-color: red;}
.right{ width: 300px; position: absolute; right: 0; top: 0; background-color: blue; }
.center{ background-color: yellow; position: absolute; left: 300px; right: 300px; top: 0;}

三、table

1
2
3
4
.container{ display: table; width: 100%; }
.left{ width: 300px; display: table-cell; background-color: red;}
.right{ width: 300px; display: table-cell; background-color: blue; }
.center{ background-color: yellow; display: table-cell;}

四、flex

1
2
3
4
.container{ display: flex; overflow: hidden;}
.left{ width: 300px; background-color: red;}
.right{ width: 300px; background-color: blue;}
.center{ background-color: yellow; flex: 1;}

五、网格grid

1
2
3
4
.container{ display: grid; grid-template-rows: auto; grid-template-columns: 300px auto 300px; }
.left{ background-color: red;}
.right{ background-color: blue; }
.center{ background-color: yellow;}