Search code examples
htmlcssdrop-down-menuflexboxmobile-website

CSS Flexbox: How to set same Height to all <li> Items independent of different Font Sizes?


Assumed we have a classic dropdown navigation on a mobile website layout. All menue items are displayed below each other:

enter image description here

ul.level_1,
ul.level_2 {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

ul.level_1 a {
    font-size: 1.5em;
    padding-bottom: 0.5em;
    padding-top: 0.5em;
}

ul.level_2 a {
    font-size: 1em;
    padding-bottom: 0.75em;
    padding-top: 0.75em;
}
 <div class="nav">
     <ul class="level_1">
         <li> bla </li>
         <li> bla </li>
         <li>
             <ul class="level_2">
                 <li> bla </li>
                 <li> bla </li>
            </ul>
        </li>
    </ul>
</div>


With same font sizes this is pretty easy, but:

Challenges:

  • Menue items of main menue ul.level_1 have font-size 1.5rem
  • Menue items of sub menue ul.level_2 have font-size 1.2rem

Therefore I want all <li> items to have the same height, so push buttons will have the same height later.

When I simply add a padding to the hyperlinks, the box heights will increase, but depending on the corresponding font size.

Is there an option available to specify the height of <li> items independent of the font size of its contained text?


Solution

  • The em unit is proportional to the font size. The simple answer is therefore to use an absolute unit like px.

    Is there any reason that you cannot just set the height of the anchors in pixels like so?

    ul.level_1,
    ul.level_2 {
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    
    ul.level_1 a {
        font-size: 1.5em;
        min-height: 30px;
        display: inline-block;
    }
    
    ul.level_2 a {
        font-size: 1em;
        min-height: 30px;
        display: inline-block;
    }
     <div class="nav">
         <ul class="level_1">
             <li> <a>bla</a> </li>
             <li> <a>bla</a> </li>
             <li>
                 <ul class="level_2">
                     <li> <a>bla</a> </li>
                     <li> <a>bla</a> </li>
                </ul>
            </li>
        </ul>
    </div>