如何清除浮动?

未清除浮动的影响

  1. 父级元素因为子级浮动引起的内部高度为0
  2. 父级元素的兄弟元素高度为0,其他样式也不能实现

01未清除浮动的影响

代码

1
2
3
4
5
6
7
<body>
<div class="father">
<div class="child1">child1</div>
<div class="child2">child2</div>
</div>
<div class="friend">friend</div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.child1,.child2,.friend{
width:50px;
height:50px;
}

.child1{
float:left;
border:1px solid blue;
}

.child2{
float:left;
border:1px solid green;
}

.friend{
border:1px solid red;
}

.father{
border:1px solid black;
}

方法1:给父元素加上 .clearfix

代码

1
2
3
4
5
6
7
<body>
<div class="father clearfix">
<div class="child1">child1</div>
<div class="child2">child2</div>
</div>
<div class="friend">friend</div>
</body>
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
.child1,.child2,.friend{
width:50px;
height:50px;
}

.child1{
float:left;
border:1px solid blue;
}

.child2{
float:left;
border:1px solid green;
}

.friend{
border:1px solid red;
}

.father{
border:1px solid black;
}

.clearfix:after{
content: '';
display: block; /*或者 table*/
clear: both;
}
.clearfix{
zoom: 1; /* IE 兼容*/
}

效果图

02给父元素加上.clearfix效果图

方法2:给父元素加上 overflow:hidden

代码

1
2
3
4
5
6
7
<body>
<div class="father">
<div class="child1">child1</div>
<div class="child2">child2</div>
</div>
<div class="friend">friend</div>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
.child1,.child2,.friend{
width:50px;
height:50px;
}

.child1{
float:left;
border:1px solid blue;
}

.child2{
float:left;
border:1px solid green;
}

.friend{
border:1px solid red;
}

.father{
border:1px solid black;
overflow:hidden
}

效果图

03给父元素加上overflow-hidden