The Float And Clearfix

Published On: 21 May 2014.By .
  • Digital Engineering

1. All floated elements are like ‘td’ (Columns) which must be wrapped in a ‘tr’ (Row) that it would not affect other elements. So the structure must like as follows:

Here FloatDiv1 / 2/ 3 are float:left or Float:right in definition. And clearfix definition is as follows:

CSS

How clearfix works?
Clearfix is just a special type of clear:both, which completely clears the effect of floated elements. Whereas clear:both clears its previous floated elements, clearfix clears its inside floated elements.
Another way of doing clearfix is to insert a blank div with clear:both definition after all floated elements, like below:

Now once again look at clearfix definition. It has a clear:both to clear all previous floats. Then look .clearfix:after definition. The :after element inserts a new element(^1 with same properties which its parent have, by default) just before closing the current element. So it will be like below in Example 1 on execution:

Which is similar to the above example2 approach. We are just inserting a blank div with the help of CSS without writing it in HTML code in clearfix:after
Now look at its other elements:
content:”.” —-> Whatever we write here will become the content of the newly created div with :after. We are inserting a ‘dot’ because some browsers and plugins remove totally blank divs. ‘font-size: 1px; height: 0; line-height: 0; visibility:hidden;’ are only to hide that ‘dot’ on any cost in all browsers.
Display:bloack sets its default behavior

And because IE7 and below versions do not understand the :after and :before thing so we use a hack in its clearfix definition (display:block; clear:both; *height:auto; *overflow:hidden;) All ”ed things are for IE7 and below. No other browser will read them.

Notes

1. Clearfix class is normally defined in all css frameworks/themes by-default. Definition may change sometimes according to use. Its common names are: .clearfix, .clearer etc. If we have any sort of normalize.css or reset.css, it will be in it.

2. Caution while using above definition of clearfix —> In its IE7 hack we are using overflow:hidden, which will hide all of its child elements, which goes out of its height. Although we are using height:auto to control that effect, but as we know position:absolute and fixed elements are treated as they are outside the normal document flow, so its parents never recognize its heights. So it gets hide in IE7 and below only. If it is happening then the only solution is to use Example 2 method instead of clearfix definition there.

^1
with same properties which its parent have, by default means if we are using :after or :before with an inline element then it will be an inline element by default, if we are not defining its display to ‘block’ to make it block level element. That’s why we use display: block; in clearfix:after definition to avoid confusions.

Related content

That’s all for this blog