两栏布局和三栏布局
现实实现中,我们使用的较多的就是两栏布局和三栏布局,下面我们将介绍几种实现方式:
两栏布局
要实现 左边固定,右边自适应 的布局效果。基本布局如下
1 | <div class="wrapper" id="wrapper"> |
使用float
1 | .left{float: left;width: 300px;height: 150px;background: red;} |
即使页面宽度比300px小左边也固定
使用table
1 | .wrapper { |
如果页面宽度比300px小,左边会缩小,高度会随内容而变大。
absolute + 负边距
1 | .left{ |
calc 方法
1 | .wrapper { |
flex 布局
1 | .wrapper { |
不会撑高
三栏布局
实现 左右模块 固定宽度,中间自适应。
流体布局
左边左浮动,右边右浮动, 中间自适应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>
.left {
float: left;
height: 200px;
width: 100px;
background-color: red;
}
.right {
width: 200px;
height: 200px;
background-color: blue;
float: right;
}
.main {
margin-left: 120px;
margin-right: 220px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div class="main"></div>
</div>
</body>
</html>
BFC 三栏布局
BFC 区域,不会与浮动元素重叠。
1 | <!DOCTYPE html> |
双飞翼布局
左右和中间都float:left, 然后利用 margin 负值的应用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
35
36
37
38
39
40
41
42
43
44
45
46
47<!DOCTYPE html>
<html lang="en">
<head>
<style>
.content {
float: left;
width: 100%;
}
.main {
height: 200px;
margin-left: 110px;
margin-right: 220px;
background-color: green;
}
//用于清除浮动
.main::after {
display: block;
content: '';
font-size: 0;
height: 0;
clear: both;
zoom: 1;
}
.left {
float: left;
height: 200px;
width: 100px;
margin-left: -100%;
background-color: red;
}
.right {
width: 200px;
height: 200px;
float: right;
margin-left: -200px;
background-color: blue;
}
</style>
</head>
<body>
<div class="content">
<div class="main"></div>
</div>
<div class="left"></div>
<div class="right"></div>
</body>
</html>
圣杯布局
html结构改变,将父元素的margin值变为和中间的一样,但也是左右和中间都float:left,再利用margin值改变位置。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
35
36
37
38
39
40
41
42<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
margin-left: 120px;
margin-right: 220px;
}
.main {
float: left;
width: 100%;
height: 300px;
background-color: red;
}
.left {
float: left;
width: 100px;
height: 300px;
margin-left: -100%;
position: relative;
left: -120px;
background-color: blue;
}
.right {
float: left;
width: 200px;
height: 300px;
margin-left: -200px;
position: relative;
right: -220px;
background-color: green;
}
</style>
</head>
<body>
<div class="container">
<div class="main"></div>
<div class="left"></div>
<div class="right"></div>
</div>
</body>
</html>
flex布局
1 | <!DOCTYPE html> |