1

I am creating a simple menu bar with CSS flexbox. My menu buttons use stretch so that the buttons are the same height as the menu bar.

The problem is that the text inside the buttons is not centered vertically if one of the divs is taller than the others.

I have tried using align-items:center and justify-content:center. While that centers the content, the buttons don't stretch to the same height as their parent anymore, which looks ugly when hovering over the divs :(

Can my flex children stretch vertically AND have their contents centered vertically?

HTML

<nav>
    <div><img src="./largelogo.png"></div>      // a tall div
    <div>Artists</div>                          // should stretch AND center
    <div>Playlists</div>
    <div>Genres</div>
</nav>

CSS

nav {
  display: flex;
  align-items: stretch;
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div:hover {
    color: #60B99A;
    background: white;
}
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Kokodoko
  • 26,167
  • 33
  • 120
  • 197

1 Answers1

1

If you also make the inner div's a flex container, you can center their text/content vertically.

Stack snippet

nav {
  display: flex;
  /*align-items: stretch;              stretch is default, so this is not needed  */
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div {
  display: flex;                   /*  added  */
  align-items: center;             /*  added  */
}

nav div:hover {
  color: #60B99A;
  background: white;
}

nav div img {
  display: block;                  /*  remove the bottom white space  */
}
<nav>
    <div><img src="http://placehold.it/100x150/f00"></div>      
    <div>Artists</div>                          
    <div>Playlists</div>
    <div>Genres</div>
</nav>

And for anyone who want the inner div themselves to be centered, use align-items: center.

Stack snippet

nav {
  display: flex;
  align-items: center;             /*  changed  */
  justify-content: center;
  background: #60B99A;
  color:white;
}

nav div:hover {
    color: #60B99A;
    background: white;
}

nav div img {
  display: block;                  /*  remove the bottom white space  */
}
<nav>
    <div><img src="http://placehold.it/100x150/f00"></div>      
    <div>Artists</div>                          
    <div>Playlists</div>
    <div>Genres</div>
</nav>
Asons
  • 84,923
  • 12
  • 110
  • 165