The main purpose of clearing float is to solve the problem that the internal height of the parent element is 0 due to the float of the child element
One, floating causes
When the parent element doesn’t give height,
The inner element expands the parent element when it is not floating
While floating, the parent element becomes a line, and the parent element collapses in height
Ii. Solutions (the third kind is generally used)
1, extra tag method (after the last floating tag, add a new tag, set it to clear: both;) (Not recommended)
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.fahter{
width: 400px;
border: 1px solid deeppink;
}
.big{
width: 200px;
height: 200px;
background: darkorange;
float: left;
}
.small{
width: 120px;
height: 120px;
background: darkmagenta;
float: left;
}
.footer{
width: 900px;
height: 100px;
background: darkslateblue;
}
.clear{
clear:both;
}
</style>
</head>
<body>
<div class="fahter">
<div class="big">big</div>
<div class="small">small</div>
<div class="clear"> Extra tag method </div> </div> <div class="footer"></div>
</body>
</html>Copy the code
If we clear the float, the parent element automatically detects the highest height of the child box and then matches it.
Advantages: Easy to understand, convenient
Disadvantages: add meaningless tags, poor semantic
2, Parent add overflow attribute (parent add overflow:hidden) (not recommended)
.fahter{
width: 400px;
border: 1px solid deeppink;
overflow: hidden;
}Copy the code
Advantages: Simple code
Disadvantages: When the content is increased, it is easy to cause the content will not be wrapped, so that the content is hidden, unable to show the element to overflow
3. Clear float with after pseudo-element (recommended)
.clearfix:after{/* False elements are normal browser clear float methods for inline elements */ content:""; display: block; height: 0; clear:both; visibility: hidden; } .clearfix{ *zoom: 1; } <body> <div class= /* The float clearing method is implemented only in Internet Explorer 6-INTERNET Explorer 7"fahter clearfix">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>
</body>Copy the code
Advantages: it conforms to the closed floating idea, and the semantic structure is correct
Disadvantages: IE6-7 does not support pseudo-elements: after, which use Zoom :1 to trigger hasLayout.
3. Clear float with before and after double pseudo-elements
.clearfix:after,.clearfix:before{
content: "";
display: table;
}
.clearfix:after{
clear: both;
}
.clearfix{
*zoom: 1;
}
<div class="fahter clearfix">
<div class="big">big</div>
<div class="small">small</div>
</div>
<div class="footer"></div>Copy the code
Advantages: Simpler code
Cons: Trigger hasLayout with Zoom :1.
To save time part of the code from the network.