Horizontal Menu with a Dynamic Number of Elements Fit As 100% Evenly

September 6th, 2012

Yikes, that title is a mouthful. So why would one need a menu that has elements fit as 100%? Well, for aesthetic reasons¬†primarily. Unfortunately (fortunately), since tables are no longer around, this has been a big issue for some web designers – especially for those who design for content management platforms or sites that have a menu that changes a lot. Sure, it’s easy to hard code widths in for each menu, but this breaks each time you want to add or remove a item from your menu. Here’s the solution:

Demo

Code

HTML

<div id="menu">
    <ul>
        <li><a href="#">Menu 1</a></li>
        <li><a href="#">Menu 2</a></li>
        <li><a href="#">Menu 3</a></li>
        <li><a href="#">Menu 4 (BIG TITLE!)</a></li>
        <li><a href="#">Menu 5</a></li>
    </ul>
</div>
‚Äč

CSS

body {
    text-align:center;
    margin:0 auto;
    width:500px;      
}

#menu {
    width:100%; 
    background:#999;  
    display:table;
}

#menu ul li {
    display:table-cell;      
}

#menu ul {
    display:table-row;      
}

#menu a {
    display:block;   
}

As you can see, this method uses some style-trickery to mimic the functionality of tables within a menu list. Menu #4 showcases the great flexibility this method offers. So go ahead, add menu items, remove some, make them big and small – and most importantly, never hard code widths again.

This entry was posted in Blog and tagged , .

5 Responses to Horizontal Menu with a Dynamic Number of Elements Fit As 100% Evenly

October 5th, 2013
Phil Hoyt says:

This seems fantastic! Going to have to try this one out real soon.

Reply
February 12th, 2014
Phil Hoyt says:

This way doesn’t like dropdown menus in firefox as they don’t allow position relative on table cells. BUT it is a great fallback for IE, so using flexbox to do modern browsers I arrived at a pretty good solution.

http://philhoyt.com/2014/02/justified-full-width-css-navigation-menu/

Reply
February 12th, 2014
Vaughn Royko says:

You are correct. I have recently done some modifications to this method that will better support drop-downs (not using flexbox though). Perhaps I will get around to posting about it. Thanks for sharing.

Reply
March 12th, 2014
Phil Flora says:

Unfortunately the display: table doesn’t supports dropdowns in Firefox, and the flexbox is not supported in < IE 10

Our visitors use even IE7…

Do you have any workaround for full width dropdown menus without JS?

Reply
March 12th, 2014
Vaughn Royko says:

Yikes, that’s new with Firefox! As for IE7/8 support, the closest I got was just adding in floats for those browsers.

Reply

Leave a Reply

*

*

TOP