First off, this example will only work in a browser that supports :nth-child, like Chrome or FireFox. I have an unordered list where the odd numbered list items are floated left and clear left, and the even numbered list items float right and clear right. Like so:
HTML:
<ul class="waterfall">
<li style="height: 100px;">1</li>
<li style="height: 200px;">2</li>
<li style="height: 50px;">3</li>
<li style="height: 100px;">4</li>
<li style="height: 200px;">5</li>
<li style="height: 50px;">6</li>
<li style="height: 50px;">7</li>
<li style="height: 50px;">8</li>
</ul>
CSS:
.waterfall {width:302px;}
.waterfall LI {
min-width: 150px;
background-color: #CCC;
margin-top: 2px;
}
.waterfall LI:nth-child(odd) {
float: left;
clear: left;
text-align: right;
}
.waterfall LI:nth-child(even) {
float: right;
clear: right;
text-align: left;
}
Goal:
All odd numbered list items should be floated to the left and be stacked on top of one another with no gap in between except the 2px margin. The same is true with the even numbered list items, except they should be floated right.
Questions a nutshell:
I’m confused as to exactly why, in this example, LI #5 can’t appear above LI #4 and LI #8 can’t appear above LI #7. In other words, why is LI #5 clearing LI #2, and LI #8 clearing LI #5? Also, why doesn’t LI #3 clear LI #2 (I don’t want it to, but if LI #5 is clearing LI #2, why doesn’t LI #3 join the party)?
TL;DR
My thoughts so far are somewhat inconclusive. It appears that the browser doesn’t want the top of an element to appear above the top of another element if the first element is defined later in the markup. Is that true?
I understand that floated elements are placed on a line, and that any floated elements not fitting on that line will just jump down to a new line and flow from there (as opposed to the free-flow concept of absolutely positioned elements). In other words, a floated element is removed from the document flow, but not quite as literally as an absolutely positioned element, because the floated element is still positioned relative to whatever line it started from and it still takes up space in the document flow. So, how is the next “line” from which floated elements hang from determined? In this example, why isn’t LI #3 clearing LI #2, but LI #5 is?
What I’m NOT looking for:
A clever solution to make this layout work by changing the markup, abandoning floats, or using JavaScript. I know how to do all that. I simply wish to be schooled in the mysterious ways of the float.
From the CSS 2.1 spec:
So
Yes. It’s covered by rules 5 and 6 above.