My Technical Notes

Wednesday, 15 October 2014

CSS clearfix AKA group aka whole class

If you wish to have a "container" css class which contains all of its children, then you are searching for the CSS clearfix hack.
If you had a left-floated div `l` and a right-floated div `r` in a container, but you wanted everything underneath it to not to go left or right of either `l` or `r`, then you want a special container css class which stops this.

<div class="whole">
    <div style="float: left; width: 100px; height: 100px; background-color: red;">
        RED
    </div>
    <div style="float: right; width: 100px; height: 100px; background-color: yellow;">
        YELLOW
    </div>
</div>
<div class="what-follows">
    WHAT FOLLOWS
</div>
with the `whole` class not defined, it looks like so:
RED
YELLOW
WHAT FOLLOWS
If we wanted the `what-follows` div to be underneath the floated divs, then we would define the `whole` class as follows:

.whole:before,
.whole:after {
    content: "";
    display: table;
} 
.whole:after {
    clear: both;
}
.whole {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

The LESS version is below:


.whole
{
    &:before, &:after {
        content: "";
        display: table;
    }      

    &:after {
        clear: both
    }

    zoom: 1;
}
With this CSS class defined, the `whole` div will act like a "whole":
RED
YELLOW
WHAT FOLLOWS

No comments: