完善clearfix

子元素和父元素相邻的垂直外边距会发生重叠,子元素的外边距会传递给父元素

使用空的table标签可以隔离父子元素的外边距,阻止外边距的重叠

display:table可以将一个元素设置为表格显示

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <style type="text/css">
 7             .box1{
 8                 width: 300px;
 9                 height: 300px;
10                 background-color: paleturquoise;
11                 
12     
13             }
14             .box2{
15                 width: 200px;
16                 height: 200px;
17                 background-color: palevioletred;
18                 /*设置一个外边距,子元素的外边距会传给相邻父元素,垂直外边距重叠,
19                  父元素也会有一个外边距*/
20                     margin-top: 200px;
21                 
22             
23                 
24             }
25             /*可以使用伪元素,选中box1的前面。添加一个块元素,但是block不可以*/
26             /*.clearfix:before{
27                 content: "";
28                 display: table;
29             }*/
30             .box4{
31                 /*添加一个边框*/
32                 border: 1px solid black;
33             }
34             .box3{
35                 width: 100px;
36                 height: 100px;
37                 background-color: brown;
38                 /*向左浮动*/
39                 float: left;/*高度塌陷*/
40             }
41             /*.clearfix:after{
42                 content: " ";
43                 display: block;
44                 clear: both;
45             }*/
46             .clearfix:before,
47             .clearfix:after{
48                 content: " ";
49                 display: table;
50                 clear: both;
51             }
52         </style>
53     </head>
54     <body>
55         <div class="box4 clearfix">
56             <div class="box3"></div>
57         </div>
58         
59         
60         <div class="box1  clearfix">
61             
62             <div class="box2"></div>
63         </div>
64     </body>
65 </html>
View Code

经过修改的clearfix是一个多功能的

既可以解决高度塌陷,又可以确保子元素和父元素垂直外边距不会重叠

猜你喜欢

转载自www.cnblogs.com/xuanxuanya/p/11813330.html
今日推荐