Search code examples
htmlcssflexboxheight

Fill height of parent with flex


I'm working on some responsive design, where I have a ul with some li elements inside, with some varying text lengths. I want the li elements to fill the height of the ul, but am having some trouble with it. The li elements have a differing height, when the content of one of them becomes too long. An example can be found below:

ul {
  display: flex; 
  align-items: center; 
  width: 650px; 
  background: red;
}

li {
  background: orange;
  border-right: 1px solid #CCC;
  list-style: none;
  padding: 10px;
  flex: 1;
  height: 100%;
}
<ul>
  <li>Longer text here 1-2-3</li>
  <li>About</li>
  <li>Payment</li>
  <li>Payment step 2</li>
  <li>Receipt</li>
</ul>

How do I make the li elements the same height, regardless of their content?


Solution

  • Replace align-items: center with align-items: stretch in ul. And remove height: 100% in li.

    ul {
      display: flex; 
      align-items: stretch; 
      width: 650px; 
      background: red;
    }
    
    li {
      background: orange;
      border-right: 1px solid #CCC;
      list-style: none;
      padding: 10px;
      flex: 1;
    }
    <ul>
      <li>Longer text here 1-2-3</li>
      <li>About</li>
      <li>Payment</li>
      <li>Payment step 2</li>
      <li>Receipt</li>
    </ul>

    As the item names suggest, this implies a menu with links?! I put a tag inside each li tag.

    Inherit the li flex rule from the parent by adding display: inherit. And add this css that centers your punctures vertically:

    ul li a {  
      margin: auto 0 auto 0;
    }
    

    ul {
      display: flex; 
      align-items: stretch; 
      width: 650px; 
      background: red;
    }
    
    li {
      display: inherit; 
      background: orange;
      border-right: 1px solid #CCC;
      list-style: none;
      padding: 10px;
      flex: 1;
    }
    
    ul li a {  
      margin: auto 0 auto 0;
    }
    <ul>
      <li><a href="">Longer text here 1-2-3</a></li>
      <li><a href="">About</a></li>
      <li><a href="">Payment</a></li>
      <li><a href="">Payment step 2</a></li>
      <li><a href="">Receipt</a></li>
    </ul>