Overflow:hidden is very popular method to clear floats without adding extra markup. I always use overflow:hidden but it becomes undesirable in few circumstances where I place absolute positioned element it cuts off the element. So we can make use of different methods.
I have explained it with two different examples below how we can clear the parent element.
A parent div with child element which has float property affects the parent div or makes it disappear.
General
<div class="parent">
<div class="child">child 1</div>
<div class="child">child 2</div>
<div class="child">child 3</div>
<div class="child">child 4</div>
</div>
<!--------------------------------------------->
.parent { width: 416px; padding: 20px ; background-color: tan; }
.child { width: 200px; height: 100px; float: left; border: 1px solid #000; margin:2px; background-color: green }
.clear { clear:both }
As you can see in the below image what happens when the child element has float property.
I have added an extra div at the end this it will clear the float and solves the issue but in the next example I will show you how to clear it without including extra markup.
Method 1
<div class="parent"> <div class="child">child 1</div> <div class="child">child 2</div> <div class="child">child 3</div> <div class="child">child 4</div> <div class=”clear”></div> </div>
After clearing the float it results in something like this.
Now I am adding a class to a parent element which forces its children to self clear, in this technique we do not have to create extra markup. Both technique results in same but I found using clearfix better as it is also implemented in HTML5 Boilerplate.
Method 2
<div class="parent clearfix">
<div class="child">child 1 </div>
<div class="child">child 2 </div>
<div class="child">child 3 </div>
<div class="chlid">child 4 </div>
</div>
<!-------------------------------------------->
.clearfix:before,
.clearfix:after {
content: ".";
display: block;
height: 0;
overflow: hidden;
}
.clearfix:after {clear: both;}
.clearfix {zoom: 1;} /* IE < 8 */
That concludes two methods to clear parent element, one uses extra markup and the other method saves the extra structural markup. Thanks to Thierry Koblentz for Clearfix Realoded.
2 Comments
Thanks that tutorial help me alot!
Thnx Chris, for mention.