set all nested li's to be width of widest li

后端 未结 6 1687
情书的邮戳
情书的邮戳 2021-01-13 21:30

How do I make nested li\'s the same width?

When I use the below code each nested li is only as wide as it\'s text + margin.

I\'d like all of the li\'s to be

6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 21:43

    You'll need to use JavaScript to set all LIs the same width as the widest LI. Here's the code if you want to use the jQuery library:

    $(document).ready(function(){
      $("#menu > li > ul").each(function() { // Loop through all the menu items that got submenu items
        var Widest=0; // We want to find the widest LI... start at zero
        var ThisWidth=0; // Initiate the temporary width variable (it will hold the width as an integer)
    
        $($(this).children()).each(function() { // Loop through all the children LIs in order to find the widest
          ThisWidth=parseInt($(this).css('width')); // Grab the width of the current LI
    
          if (ThisWidth>Widest) { // Is this LI the widest?
            Widest=ThisWidth; // We got a new widest value
          }
        });
    
        Widest+='px'; // Add the unit
    
        $(this).parent().css('width',Widest);
        $(this).children().css('width',Widest);
      });
    });
    

    CSS change:

    #menu li ul li {
      padding: 0 9px;
      background: #BDCCD4;
      padding: 0 20px;
    }
    

    Check it out at JSFiddle.

    Edit: Fixed my misunderstanding. :)

提交回复
热议问题