Arkana
Arkana

Reputation: 2889

Proper use of 'clear' property (related to floated elements)

I have a few doubts with the clear:x; property.

Preludes: I need to make a list, and the elements must be placed as a grid. Also, I need to make it compatible with IE7 or greater.

Here's my HTML:

<ul>
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
</ul>

And the CSS (ul + li are the trick for emulating nth-of-type; in the real code I have about ten elements by row):

ul {list-style:none; margin:0; padding:0;}
ul li{background:pink; border:1px solid red; height:1em; width:1em; float:left; margin:0 .2em .2em 0; padding:.3em}
ul li + li + li {clear:left;}
ul li + li + li +li {clear:none;}

This works well. Here's a fiddle.

BUT, in first place my intuition makes me put a clear:right in the second li. But that code doesn't work, here's the corresponding fiddle.

Why this doesn't work? It isn't expected that the second li will clear the third li at his right?

Upvotes: 2

Views: 98

Answers (2)

Mr. iC
Mr. iC

Reputation: 129

The clear:right property doesn't prevent elements from being placed in that space after the cleared element. It prevents the element from being placed where there are already elements floated to the that direction before it - ahruss

You are using a float:left; thats when you need to use a clear:left;
If you are using a float:right; than you can cause a line break with a clear:right;
You can check out this 2 behavior here Here's a Fiddle

So when you use a clear:left on the "C" li then it will cause a line break.
You could also use a clear:both; to cause a line break.
or you just use a <br />.

Upvotes: 1

Teemu P&#228;rssinen
Teemu P&#228;rssinen

Reputation: 11

It doesn't work because clear doesn't clear elements that come after the element in document order. There are no elements in your fiddle that are both: positioned on right-hand side of your element where clear: right is set and come before that element in document order.

I hope this clarifies your question :-)

Upvotes: 1

Related Questions