Reputation: 5124
I am hoping to find a way to create a simple two-column list with variable height elements without using two wrapper elements for the columns, or any javascript.
https://stackoverflow.com/a/16821155/2026098 mentions that floating odd elements to the left and even elements to the right might do the trick, but it seems to fail when the elements' heights are too variable.
<div class="two-column-list">
<div class="element odd">A few words</div>
<div class="element even">A few sentences</div>
<div class="element odd">Many paragraphs</div>
<div class="element even">One sentence</div>
<div class="element odd">Many paragraphs</div>
</div>
.element.odd { float: left; }
.element.even { float: right; }
See http://jsfiddle.net/PF62T/3/.
The gray boxes are odd and red ones are even. When making one of the odd boxes not high enough, the last of the even (red boxes), even though floated right, seems to want to occupy the space available on the left. Is there any way I can force the boxes to always stick to the left or right edge, no matter their height?
I don't want to use CSS3 columns because I need to support IE8+. I am using angular so I can easily add different classes for odd and even elements, so this isn't a problem, either.
I realise that using two wrappers would be the most solid solution, but I get the feeling the answer is out there somewhere :P My main reason for not wanting wrapper elements is that I need to show all the elements in a single column on mobile, in which case the wrappers would mess up their order.
Upvotes: 1
Views: 73
Reputation: 103780
You can fix this by using clear:left;
to the floated left elements and clear:right
on the floated right elements.
See this FIDDLE
div:nth-child(odd) {
float: left;
clear:left; /* ADD THIS */
background-color: red;
}
div:nth-child(even) {
float: right;
clear:right; /* ADD THIS */
}
Upvotes: 2