Search code examples
cssmenu

CSS: Fixed with horizontal menu, with variable width tabs, using ul


I have a horizontal menu. The markup looks like this:

<ul class="menu">
   <li>Item 1</li>
   <li>Longer Item 2</li>
   <li>Item 3</li>
</ul>

Submenus and suckerfish dropdowns will come later.

The ul needs to span the width of the page (e.g. 100% or 1000px).

The lis should vary in width based on their content.

So the result would look like this:

-----------------100% of page------------
|--Item 1--|--Longer item 2--|--Item 3--|

Now it is easy to do this by fixing a width for each li tag, but because the menu will be CMS driven I need to allow the width of the tabs to vary automatically. With a table this would be trivial, but I can't think of a way to do it with a ul.


Solution

  • Here's my jquery solution:

    var actualWidth = 1000;
    var totalLIWidth = 0;
    
    // Calculate total width of list items
    var lis = $('ul li');
    
    lis.each(function(){
        totalLIWidth += $(this).width();
    });
    
    // Work out how much padding we need
    var requiredPadding = Math.round(((actualWidth-totalLIWidth)/lis.length)/2);
    
    // To account for rounding errors, the error is going to be forced into the first tab.
    var roundingErrorFix = (requiredPadding*lis.length*2)+totalLIWidth-actualWidth;
    
    // Apply padding to list items
    lis.each(function(i) {
        if(i==0) {
            $(this).css('padding-left',requiredPadding-roundingErrorFix+'px')
                .css('padding-right',requiredPadding-roundingErrorFix+'px');
        }
        else {
            $(this).css('padding-left',requiredPadding+'px')
                .css('padding-right',requiredPadding+'px');
        }
    });