This is one problem that has been bugging me for years now.

I often have the requirement to make a menu that would fill 100% of my site width (e.g. 900px).

This is easy to accomplish with tables, simply:

<table width="100%">
  <tr>
    <td>menu item 1</td>
    <td>menu item 2</td>
    <td>menu item 3</td>
    and so on...
  </tr>
</table>

And the table will adjust the each cell width according to the number of elements that are in the table.

But with CSS, this type of horizontal menu seems impossible to me?

Has anyone got any information/link to an article that solves this issue?

Marko

4 answers

o.k.w 2355
2
points
This was chosen as the best answer

You might want to give display: table a try.

CSS:

#menu {
 width: 100%;
 display: table; /* note this */
 list-style-type: none;
 padding: 0;
 margin: 0;
 border: solid 1px red;
}
#menu li{
 width: auto;
 display: table-cell; /* note this */
 text-align: center;
 border: solid 1px black;
}

HTML:

<ul id="menu">
<li>Menu1</li>
<li>Menu2</li>
<li>Menu3</li>
<li>Menu4</li>
</ul>

Note that this probably will not work on the older browsers.

Answered over 6 years ago by o.k.w
  • That's very smart, I'm gonna give it a try! Marko Ivanovski over 6 years ago
1
point

http://webtint.net/tutorials/future-of-css-the-flexible-box-model/

Answered over 6 years ago by Nathan Duran
  • That's an excellent article, thanks a lot! Now we wait for 5 years so IE provides support for it :) Marko Ivanovski over 6 years ago
0
points

I've considered using jQuery to divide the width of the ul.menu with the number of elements inside - like:

var numberOfLinks= $('ul.menu li').size();
$('ul.menu li').width($(ul.menu).width() / numberOfLinks);

But without javascript it would turn ugly.

Any suggestions?

Answered over 6 years ago by Marko Ivanovski
0
points

I'm pretty sure this works for what you want:

<ul style="width:100%;">
    <li style="float:right; width:25%;>Menu Item one</li>
    <li style="float:right; width:25%;>Menu Item two</li>
    <li style="float:right; width:25%;>Menu Item three</li>
    <li style="float:right; width:25%;>Menu Item four</li>
</ul>

Understand that the width of the list items needs to be 100% divided by the number of list items.

Answered over 6 years ago by xonecas
  • Yes that's easy if I know there's going to be 4 items in the menu, what if you add a 5th item? :) Marko Ivanovski over 6 years ago