Sunday, May 31, 2009

Positioning of a DIV Box: Float and Clear Float

One of the reasons I did not use DIV with CSS as the layout at the beginning was that I did not know how to position the DIV boxes properly. I could use "float" property in the CSS stylesheet to place a DIV element to the left or to the right. However if I added another DIV element below the floated elements, the newly added element would not be at the place that I wanted it to be. Are you encountering the same issue right now? If so, maybe you made the same mistake I did.

The default display format for DIV elements is "block" which means the DIV elements are laid out vertically, starting at the top. If we want two DIV elements side by side, we can add a "float" property to the elements. This property specifies whether an element should float (to the left or to the right) or not. If so, the floated element will be shifted to the left or to the right as far as it can go depending on what value we assign to it. Now if we want to add another DIV element below these floated elements, we might forget to do one thing: adding the "clear" property to the newly added element.

This "clear" property specifies which sides of an element cannot be adjacent to any floated elements. In this case, we should apply "clear:both" property to the newly added element so that it will not wrap around any floated elements and instead it will go right below them. So the key here is: after applying the floats, make sure you CLEAR them. Good luck!