Reputation: 267049
I'm trying to create a horizontal UL which always shows 3 items per line. The tricky part is that the items can be of varying widths. For example:
<ul class="items">
<li>
<input type="checkbox" id="work" />
Work items
</li>
<li>
<input type="checkbox" id="shopping" />
Shopping
</li>
<li>
<input type="checkbox" id="financial" />
Financial Information & Tips
</li>
</ul>
etc.
I want to do it so its essentially like using a table, where it always shows 3 items per line, and the checkbox of each item is always on the same line as its text.
How can I do it?
Here's the current code I'm using, but it doesn't show the items evenly, often the last checkbox ends up on line 1 and the text is pushed to the next line.
ul.items
{
text-align: center;
list-style-type: none;
width: 400px;
}
ul.items li
{
display: inline;
}
Upvotes: 1
Views: 10987
Reputation: 207881
Try the CSS nth-child
selector. Works regardless of the width.
I also removed your display:inline
rule and replaced it with a float:left;
.
ul.items li:nth-child(3n+4) {
clear:left;
float:left;
}
For more info on nth-child
, see https://developer.mozilla.org/en-US/docs/CSS/:nth-child
Upvotes: 14
Reputation: 2224
I like to use float for this
ul.items
{
text-align: center;
list-style-type: none;
width: 400px;
}
ul.items li
{
float: left;
display: inline;
}
.clear { clear: both; }
with this html:
<ul class="items">
<li>
<input type="checkbox" id="work" />
Work items
</li>
<li>
<input type="checkbox" id="shopping" />
Shopping
</li>
<li>
<input type="checkbox" id="financial" />
Financial Information & Tips
</li>
<li class="clear"></li>
</ul>
Demo here: http://jsfiddle.net/hG3Us/
Upvotes: 4