8
<div>
  <ul>
    <li>First</l1>
    <li>Second</li>
    <li>Third</li>
    <li>Fourth</li>
  </ul>
</div>


div {
  width: 100%;
}
li {
  list-style: none;
  float: left;
}

With CSS, is there a way to make the LI tags automatically fill the whole width of the parent div, evenly? So they'd each take up 25%.

Specifying 'width' as 25% would obviously work but it's not solution I'm after. The menu in question is dynamically created and new items are created and deleted at times.

Cheers

Allan Thomas
  • 3,481
  • 5
  • 26
  • 29

3 Answers3

11

I think you have three options:

  1. Use JavaScript to calculate the sizes

  2. Use a table, as discussed in this question (this is actually not a bad option — it’s pure HTML and CSS

  3. If you’re only targeting new browsers, you can use the new flexible box component of CSS (shown here with a couple of vendor prefixes):

    ul{
        padding: 0;
        display: -webkit-box;
        display: -moz-box;
        display: box;
    }
    li{
        list-style: none;
        list-style:none;
        text-align: center;
        -webkit-box-flex: 1;
        -moz-box-flex: 1;
        box-flex: 1;
    }
    
Community
  • 1
  • 1
s4y
  • 50,525
  • 12
  • 70
  • 98
1
ul{
  display:block;
  margin:0;
  padding:0;
}

li{
  display:block;
  width:25%;
  margin:0;
  padding:0;
  float:left;
  list-style:none;
}
beerwin
  • 9,813
  • 6
  • 42
  • 57
  • My question stated that a percentage width in this case is not the solution I'm after. – Allan Thomas Oct 13 '11 at 18:54
  • otherwise you could give them fixed widths, if you know how wide the div would be, as it fits in some other element (with that 100% width) – beerwin Oct 13 '11 at 18:59
  • I know it would work for a static menu. The menu I'm asking the question for has items added and deleted occasionally through a CMS therefore this is not the solution. – Allan Thomas Oct 13 '11 at 19:10
  • so, if you have three items, those three should fill the entire div, or if you have 5 and so on? – beerwin Oct 13 '11 at 19:13
  • Yes. I have a solution written in jQuery because I couldn't think if it was possible purely with CSS – Allan Thomas Oct 13 '11 at 19:27
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4244/discussion-between-beerwin-and-allanb) – beerwin Oct 13 '11 at 19:28
-1

In my searches from a while back, I didn't come across anything that lets you dynamically specify the list item width. If you're also asking how to have your list be horizontal instead of vertical, use:

li {
  display: inline;
  float: left;
}
Tym Pollack
  • 125
  • 2
  • 9