Search code examples
htmlcssmenumenuitem

CSS - How to get variable width <LI> in my Vertical Nav Menu <UL>


I have a vertical navigation menu <UL> with every <LI> as long as the widest element.

https://i.sstatic.net/1satJ.png

How can I use CSS to resize each <LI> to only be as wide as necessary, while maintaining the vertical orientation?

I've tried .main-navigation li {display: inline-block;}and .main-navigation li {float: left;}but they both turned my menu horizontal which I don't want.

My <UL> is called.main-navigation ul if that helps. Thanks in advance for any assistance!


Solution

  • Better apply styles to the elements inside the LI, not the LI itself.

    .main-navigation ul{
      list-style: none
    }
    
    .main-navigation li{
      display: block;
      padding: 10px 0;
      text-align: center
    }
    
    .main-navigation a{
      text-decoration: none;
      display:inline
    }
    
    .main-navigation a:hover{
      border-bottom: 1px solid #f00
    }
    <html>
    <head>
    
    </head>
    <body>
    <div class="main-navigation">
    <ul>
    <li><a href="#">Link</a></li>
    <li><a href="#">Long Link</a></li>
    <li><a href="#">Even longer Navigation Link</a></li>
    </ul>
    </div>
    </body>
    </html>