Simple tricks to clear the floats in CSS

Simple tricks to clear the floats in CSS

3 min. read

HTML code

<div id="container">
    <div id="box-1"></div>
    <div id="box-2"></div>
</div>

Styles applied to above HTML code

#container
{
    width:100px;
}

#box-1
{
    background-color:#000;
}

#box-2
{
    background-color:#00ad7a;
}

#box-1, #box-2
{
    float:left;
    width:50px;
    height:100px;
}

When you apply these CSS rules to the above HTML the resulting height of the div#container element will be 0px but it need to be 100px. You can inspect the div#container element and check it's dimension in the browser developer tool.

See result in the fiddle below

So, the problem is, height of the div#container element turned out to 0px which should be 100px in our case, to solve this issue i.e "making the parent element cover it's child elements completely" you can use any of the tricks that I have mentioned below.

Trick 1: By adding extra HTML (old way)

Add the following HTML code as the last child element of the div#container element.

<br class="clearfix" />

The complete HTML code will look like:

<div id="container">
    <div id="box-1"></div>
    <div id="box-2"></div>
    <br class="clear" />
<div>

and then apply the following CSS to the <br /> element

.clear
{
    clear:both;
}

Trick 2: Using CSS overflow property

Just add the below CSS rule to the original CSS rules

#container
{
    overflow:hidden;
}

or you could use

#container
{
    overflow:auto;
}

Trick 3: Clearfix class - 1

This trick provides support for IE < 8

Add the clearfix class to div#container element

<div id="container" class="clearfix">

then add the below CSS rules to the original CSS rules.

.clearfix:before, .clearfix:after
{
    content:'';
    display:table;
}

.clearfix:after
{
    clear:both;
}

.clearfix
{
    zoom:1; /* For IE 6 & 7 */
}

Trick 4: Clearfix class - 2

Use this trick if you don't want to provide support for IE < 8

Add the clearfix class to div#container element

<div id="container" class="clearfix">

then add the below CSS rules to the original CSS rules

.clearfix:after
{
    content:'.';
    display:block;
    clear:both;
    height:0;
    visibility:hidden;
}

or you could use

.clearfix:after
{
    content:'';
    display:table;
    clear:both;
}

Trick 5: contain-floats

W3C has provided a solution for handling floats, that is "contain-floats" value for min-height CSS property, read more about it here.

Just add the below CSS rule to the original CSS rules.

#container
{
    min-height:contain-floats;
}
Write comments