Home > front end >  How to automatically adjust ul position based on number of li's in css?
How to automatically adjust ul position based on number of li's in css?

Time:04-27

I have a set of "Unordered lists" and the display will show 6 of them when the user is logged into the site. When the user logs out only 3 of them will show up. I want to align the ULs to center and auto adjust based on number of LIs. My css is as below:

@media (min-width: 64em)
.usa-header--basic .usa-nav {
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
    display: flex;
    padding: 0 0 0.25rem 0.5rem;
    width: 100%;
}
@media (min-width: 64em)
.usa-nav {
    float: right;
    position: relative;
}    
ul.usa-nav__primary.usa-accordion {
        width: 100%;
        padding-top: 6rem; //intentional padding
        position: initial
    }

This CSS works as below when the user is logged in:

enter image description here

However, when the user logs out only 3 menu item will show up. So with the same above css, the screen looks like below:

enter image description here

How to fix this so the menu items align automatically to the center?

HTML for the menu portion:

<nav  role="navigation">
   <ul  role="navigation">
      <li >
         <a href="/" >
         <span>Menu1</span>
         </a>
      </li>
      <li >
         <button  aria-expanded="false" aria-controls="basic-nav-section-2">
         <span>Menu2</span>
         </button>
         <ul id="basic-nav-section-2"  hidden="">
            <li >
               <a href="/#">
               <span>Submenu1</span>
               </a>
            </li>
            <li >
               <a href="/#">
               <span>Submenu2</span>
               </a>
            </li>
         </ul>
      </li>
      <li >
         <button  aria-expanded="false" aria-controls="basic-nav-section-3">
         <span>Menu3</span>
         </button>
      </li>
      <li >
         <a href="/#" >
         <span>Menu4</span>
         </a>
      </li>
      <li >
         <a href="/#" >
         <span>Menu5</span>
         </a>
      </li>
      <li >
         <a href="/#" >
         <span>Menu6</span>
         </a>
      </li>
   </ul>
</nav>

CodePudding user response:

Here is a potential solution for you. :) Just use flex on the list itself.

display: flex;
justify-content: center;

And then simply give some margin to li elements.

https://codepen.io/Juka99/pen/QWaXZER

  • Related