Stephan Kulla
Stephan Kulla

Reputation: 5067

Does "clear:right" affect left floated elements?

Imagine I have the following markup:

<div class="right">Box right 1</div>
<div class="right">Box right 2</div>
<div class="left">Box left</div>

<p>... long text ...</p>

and the following CSS:

.right { float:right; clear: right; }
.left { float:left; clear: left; }

div { /* some styles for the divs */ }

This will result in the following (see jsFiddle demo):

result

This is not the result I expected. I thought the left box is also floated on the top like here:

expected result

Question: Why is the left box not floated on the top? The text inside <p> begins on top although its written after the left box in the markup. So I would expect, that also div.left starts on top.

Note: After deleting clear: right in the CSS of the class .right the left box is top floated (see jsFiddle demo):

after deleting clear:right

So it seems, that clear:right has a effect on left-floating elements...?!

Note 2: Also this markup would float the boxes as expected (jsFiddle demo):

<div class="right">Box right 1</div>
<div class="left">Box left</div>
<div class="right">Box right 2</div>

<p>... long text ...</p>

Upvotes: 2

Views: 325

Answers (1)

BoltClock
BoltClock

Reputation: 723708

As you may have suspected, clear: right will only clear right floats, not left floats. The left float is not being affected by clearance — at least, not directly. It's actually obeying rule #5 in the following list from the spec:

Here are the precise rules that govern the behavior of floats:

[...]

  1. The outer top of a floating box may not be higher than the outer top of any block or floated box generated by an element earlier in the source document.

This is because clearance is designed to only affect floats that come before an element in the source.

Since the second right float is clearing the first one, it sits underneath the first one. And since the left float comes after both of them in the source, it cannot float any higher than the second float because of the clearance that affects the second float.

If you move the left float all the way to the top in the source:

<div class="left">Box left</div>
<div class="right">Box right 1</div>
<div class="right">Box right 2</div>

<p>... long text ...</p>

You'll see the same expected behavior. This is where the difference between clear: right and clear: left/both becomes significant. If the boxes were made to clear in both directions, only then will the left float be cleared by both the right floats.

Upvotes: 4

Related Questions