CSS清除浮动

未清除浮动时:

代码

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 .box{
8 width: 600px;
9 border: 2px solid red;
10 }
11 .d1{
12 width: 100px;
13 height:100px;
14 background-color: blue;
15 float: left;
16 }
17 .d2{
18 width: 100px;
19 height:100px;
20 background-color: green;
21 float: right;
22 }
23
24 </style>
25 </head>
26 <body>
27 <div class="box clearfix">
28 <div class="d1"></div>
29 <div class="d2"></div>
30 </div>
31 </body>
32 </html>

页面展示:父级元素高度没有将子元素包围

CSS清除浮动

清除浮动方法一:添加元素及其clear属性

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 .box{
8 width: 600px;
9 border: 2px solid red;
10 }
11 .d1{
12 width: 100px;
13 height:100px;
14 background-color: blue;
15 float: left;
16 }
17 .d2{
18 width: 100px;
19 height:100px;
20 background-color: green;
21 float: right;
22 }
23 .clear{
24 clear: both
25 }
26 </style>
27 </head>
28 <body>
29 <div class="box clearfix">
30 <div class="d1"></div>
31 <div class="d2"></div>
32 <div class="clear"></div>
33 </div>
34 </body>
35 </html>

清除浮动方法二:父元素设置overflow:hidden

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 .box{
8 width: 600px;
9 border: 2px solid red;
10 overflow: hidden;
11 }
12 .d1{
13 width: 100px;
14 height:100px;
15 background-color: blue;
16 float: left;
17 }
18 .d2{
19 width: 100px;
20 height:100px;
21 background-color: green;
22 float: right;
23 }
24 </style>
25 </head>
26 <body>
27 <div class="box clearfix">
28 <div class="d1"></div>
29 <div class="d2"></div>
30 </div>
31 </body>
32 </html>

清除浮动方法三:父元素设置伪元素清除浮动

 1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8">
5 <title></title>
6 <style type="text/css">
7 .box{
8 width: 600px;
9 border: 2px solid red;
10 }
11 .d1{
12 width: 100px;
13 height:100px;
14 background-color: blue;
15 float: left;
16 }
17 .d2{
18 width: 100px;
19 height:100px;
20 background-color: green;
21 float: right;
22 }
23 .clearfix:after{
24 display: block;
25 content:'';
26 clear: both;
27 height:0;
28 }
29 </style>
30 </head>
31 <body>
32 <div class="box clearfix">
33 <div class="d1"></div>
34 <div class="d2"></div>
35 </div>
36 </body>
37 </html>

清除浮动后的页面展示

CSS清除浮动

返回
顶部