Reputation: 577
That is, without defining a specific 'width' amount for each individual item. As in, the widest element (by its content) sets the width for each of the other elements.
Additionally, how do I span said list 100% across its container, also keeping each item the same width?
Upvotes: 0
Views: 8153
Reputation: 125443
Use css tables with a fixed table layout.
The result will be each <li>
sharing an equal portion of the <ul>
no matter how many items there are in the list.
ul
{
display: table;
table-layout: fixed;
width: 100%;
border: 1px solid #c2c2c2;
box-sizing: border-box;
}
li
{
text-align: center;
display: table-cell;
border-right: 1px solid #c2c2c2;
}
Upvotes: 1
Reputation: 532
If I understand correctly:
You want that width to be the width of the widest list item's content
You also want a way to evenly space list items across a container, this seems incompatible with 3, because then they won't be evenly spaced by content but by container size.
So I'm assuming you want two different solutions.
I think you can do
<style>
ul, li{float:left;margin;padding:0;display:block;}
li {clear:left;width:100%;margin:1px 0;background:#03a;}
</style>
<ul>
<li>Item 1</li>
<li>Item 2 which is longer</li>
<li>Item 3</li>
</ul>
works in some browsers. I seem to remember it not working in IE, and having to make it work using css expressions.
The idea is that the ul and li's are floated to shrink them to their content width. The li's are cleared and set to 100% of their container width, the same container that is shrunk to their size.
--
Your other option is impossible in CSS unless you know the number of list items. Though if you don't know the number of list items it means there is scripting going on either server side or client side, and you can find out the number of items. :)
I've solved this in the past by giving the ul a class with the number of children in it, and using lots of CSS rules and hoping one sticks.
eg
<style>
ul.lis1 li {width:100%}
ul.lis2 li {width:50%}
ul.lis3 li {width:33.3%}
ul.lis4 li {width:25%}
/* ... you can keep going forever here, though there'll be a point at which they become too thin and your UI breaks anyway, */
</style>
<ul class="lis4"> <!-- lis4 is generated by PHP or Ruby or whatever -->
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
Upvotes: 3
Reputation: 50105
You'll need to float them for this:
ul {
list-style: none;
}
ul li {
float: left;
width: 100px; /* Or whatever arbitrary amount you want */
}
The list should automatically span the width of the container - its a block element.
Upvotes: 0