Home > Article > Web Front-end > What are the methods and advantages and disadvantages of clearing floats?
Why do we need to clear floats?
The following example is the effect of floating on elements
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <style type="text/css"> .box1 { width: 100px; background: #999; } .box2 { width: 100px; height: 40px; } .box3 { width: 100px; height: 40px; background-color: #333; } </style></head><body> <p class="box1"> <p class="box2"></p> </p> <p class="box3"></p></body></html>
The result after adding float: left attribute to box2 is as follows
As shown in the figure, since box1 has no height set, box3 Automatic filling, if so, the page will be cluttered. Therefore, we need to clear this kind of float
The following are several ways to clear the float
(1) clear: both
By adding the p tag under the floating element and setting clear: both attributes
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <style type="text/css"> .box1 { width: 100px; background: #999; } .clear { clear: both; } .box2 { width: 100px; height: 40px; float: left; } .box3 { width: 100px; height: 40px; background-color: #333; } </style></head><body> <p class="box1"> <p class="box2"></p> <p class="clear"></p> </p> <p class="box3"></p></body></html>
Advantages: simple, less code, good browser support
Disadvantages: added meaningless tags
(2)overflow: hidden
Clear the float by adding the overflow: hidden attribute to the parent element of the floating element
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <style type="text/css"> .box1 { width: 100px; background: #999; } .clear { overflow: hidden; zoom: 1; /*处理兼容性问题*/ } .box2 { width: 100px; height: 40px; float: left; } .box3 { width: 100px; height: 40px; background-color: #333; } </style></head><body> <p class="box1 clear"> <p class="box2"></p> </p> <p class="box3"></p></body></html>
Advantages: Simple, less code, good browser support
Disadvantage: excess content will be hidden
(3) Add after pseudo-class
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <style type="text/css"> .box1 { width: 100px; background: #999; } .clear:after { clear: both; content: ""; display: block; visibility: hidden; } .box2 { width: 100px; height: 40px; float: left; } .box3 { width: 100px; height: 40px; background-color: #333; } </style></head><body> <p class="box1 clear"> <p class="box2"></p> </p> <p class="box3"></p></body></html>
Advantages: good browser support
Disadvantages: lots of code
The third method is the method used by many browsers now, so clear the float It is best to use the after pseudo-class
The above is the detailed content of What are the methods and advantages and disadvantages of clearing floats?. For more information, please follow other related articles on the PHP Chinese website!