Reputation: 47061
In this thread: What is a clearfix?
I saw the best answer says the clearfix can be added directly to the last floating element:
With clearfix, you only need to
write HTML code:
<div class="clearfix">
<div style="float: left;" class="clearfix">Sidebar</div>
</div>
and CSS code:
.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
However, when I tried to add clearfix
to the floating element, it doesn't work at all (as can be seen in the snippet below) :
.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
div#container {
background-color: green;
width: 50%;
display: block;
margin: auto;
}
.floating {
float: left;
margin: 1px;
background-color: yellow;
}
<div id="container">
<div class='floating'>1</div>
<div class='floating clearfix'>2</div>
</div>
As can be found in the result, the #container
's height is still 0
. It seems that the clearfix doesn't work and cannot be added to the last floating element directly. Is it true? Does anyone have ideas about this?
Upvotes: 1
Views: 622
Reputation: 5291
You need to add the :after
element that should clear the children at the end of the container, not inside the floating element itself. All you have to do is give the container the class clearfix
, like this:
<div id="container" class="clearfix">
<div class="floating">1</div>
<div class="floating">2</div>
</div>
Upvotes: 3
Reputation: 2223
You've to use the clearfix
on the container
.
.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}
div#container {
background-color: green;
width: 50%;
display: block;
margin: auto;
}
.floating {
float: left;
margin: 1px;
background-color: yellow;
}
<div id="container" class="clearfix">
<div class='floating'>1</div>
<div class='floating'>2</div>
</div>
Upvotes: 4