How the CSS Clear Property Works
posted by Kravvitz at 7:14 PM on Jan. 16th, 2009
Categories: CSS, Beginner, Intermediate 3 commentsPerhaps the time has come for me to explain how the clear property works. When you give an element clear:left, that tells the rendering engine that the top edge of that element must sit below all left floated elements that precede it within the "float scope". (If there's a better term for it, please tell me.) Elements with clear:right must likewise sit below preceding right floated elements within the float scope. Giving an element clear:both means that you want it to clear left floated and right floated elements.
So what is a float scope?
Float scope means that if the element with clear:left applied to it is a descendant of a floated or absolutely positioned element, it will only clear the bottom edges of other descendants of that common ancestor.
Float Scope in action
Consider this, a common two column layout in which one is floated left and the other has a margin on its left side so they'll sit next to each other. Now what happens if you use clear:left in the non-floated column (assuming that that element is in the same float scope as the left column)? It causes that element to sit below the bottom edge of the left column. (See example 1.) That's not what you really wanted to happen, was it? The solution is to either float the right column (example 2) or to add a floated wrapper element to the contents of the right column (example 3). Either way the content of the right column will now be in a different float scope so clear:left will not make an element in it clear the left column. Floating the right column tends to only be a good solution when it has a set width though.
What else is the clear property useful for?
The clear property allows you to make a container of floats expand vertically to contain them. You see, if you have a non-floated element after floats, then the floats may overlap it, but if you make that element a clearing element, it will sit below the floats, and since it's in the flow it will cause the parent to expand in height (assuming of course the parent doesn't have a fixed height or a max-height that's not large enough).
Nice lesson!
Arem 5:33 AM on Feb. 24th, 2009This site is like a classroom, eexpct I don't hate it. lol
Rain 1:51 PM on Sep. 1st, 2011Login or Register to post a comment