A clearfix class is a way for an element to automatically clear left and right float on its child elements. This eliminates the need to add extra child element to clear float. This works by adding ::after pseudo element on container element which has floar clearing style clear:both
.
Example – float left without clearing float
This example has no clear float on outer div’s child elements. This has caused some undesired effects.
<style type="text/css" media="screen"> .outer { background-color:lightblue; padding: 5px; } .left { background-color:lightgreen; width:50px; margin: 5px; float:left; } </style> <div class="outer"> <div class="left">First</div> <div class="left">Second div</div> </div> <div>footer div</div>
Example – float left and clearing float using extra child element
This example adds extra child div (with clear:both) inside outer div.
<style type="text/css" media="screen"> .outer { background-color:lightblue; padding: 5px; } .left { background-color:lightgreen; width:50px; margin: 5px; float:left; } </style> <div class="outer"> <div class="left">First</div> <div class="left">Second div</div> <div style="clear:both"></div> </div> <div>footer div</div>
Example – float left and clearing float using clearfix
This example is using clearfix hack. Here outer div has class=clearfix. Class clearfix has an ::after pseudo element which clears both left and right float. Note that if you need IE8 support, you may want to use :after instead of ::after.
<style type="text/css" media="screen"> .clearfix::after { content: ""; display: block; clear: both; } .outer { background-color:lightblue; padding: 5px; } .left { background-color:lightgreen; width:50px; margin: 5px; float:left; } </style> <div class="outer clearfix"> <div class="left">First</div> <div class="left">Second div</div> </div> <div>footer div</div>