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

前端 未结 5 522
春和景丽
春和景丽 2020-12-15 09:40

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

  • Item 1
  • Longer Item 2
相关标签:
5条回答
  • 2020-12-15 10:36

    This is a case for

    Display:Table-Man

    ul {
      display: table;
      width: 100%;
      table-layout: fixed;
    }
    li {
      display: table-cell;
    }
    

    Unfortunately, you should abandon the thought of supporting IEs 6 and 7, but else this is the way to go (or switching to HTML tables, which might or might not be so far away from the semantic content of the markup).

    0 讨论(0)
  • 2020-12-15 10:39

    If you're happy using JavaScript, jQuery could solve the issue as follows

    var $menu, totalwidth;
    
    $menu = $('ul.menu');
    totalwidth = ($menu.width()/100);
    
    $('ul.menu li').each(function(){
        this.css('width',String(Math.floor(this.width()/totalwidth))+'%');
    });
    
    $menu.css('width','100%');
    

    That's untested, but looks right to me. Comment if you've any questions at all.

    0 讨论(0)
  • 2020-12-15 10:43

    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');
        }
    });
    
    0 讨论(0)
  • 2020-12-15 10:45

    I reckon boldewyn's suggestion should work. I would use this approach for modern browsers and then use conditional comments to feed the following to ie6/7, so that the nav looks ok there , though won't span the 100% width.

    ul {
      width: 100%;
    }
    li {
      float:left; // or display:inline-block;
    }
    
    0 讨论(0)
  • 2020-12-15 10:45

    If you are trying to style the ul (such that it stretches across the entire page), your best bet is to wrap it in a div, and style the div, and then allow the ul to just stretch as far as its content carries it

    0 讨论(0)
提交回复
热议问题