Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does CSS clearing really work?

Tags:

css

layout

I have a <div> that I want to be on a line by itself. According to W3Schools, this rule:

div.foo {
  clear: both;
}

...should mean this:

"No floating elements allowed on either the left or the right side."

However, if I float two <div> elements left, and apply the rule above to the first one, the second one does not budge.

On the other hand, if I apply "clear: left" to the second <div>, it moves down to the next line. This is my normal approach, but I don't understand why I have to do it like this.

Is the W3Schools description above poorly stated, or am I missing something? Is a clearing rule only able to move the element to which it is applied?

Answer

Thanks Michael S and John D for the good explanations. Warren pointed to the CSS2 spec, and that's where I found this answer (emphasis mine):

This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.

So: clear only affects the position of the element to which it is applied, relative to elements that appear before it the code.

Disappointing that I can't tell my <div> to make other divs move down, but them's the breaks. :)

like image 739
Nathan Long Avatar asked Oct 17 '08 15:10

Nathan Long


2 Answers

When you apply clear to an element, it will move THAT element so that it doesn't have items left or right of it. It does not re-position any of the other elements, it simply moves the element to a position where nothing is around it.

Edit

Items above the item cleared are not moved, items below the element COULD be moved. Also note the additional comment in the comments

like image 60
Mitchel Sellers Avatar answered Nov 16 '22 00:11

Mitchel Sellers


Your css is parsing "correctly." Your second div is still floated left, so even after you clear the first one, if there's room widthwise for the second one, it will fit floated left at the topmost point it can.

like image 23
John Dunagan Avatar answered Nov 16 '22 00:11

John Dunagan