Dustin Dustin - 3 months ago 40
CSS Question

Flexbox navbar, stretch links to be equal heights

I have a navbar that has some links that wrap on to 2+ lines when the viewport is somewhat narrow. I'd like to make all of the nav items the same height and keep their text vertically centered. So far I've been able to vertically center everything but I'm having trouble getting the height of the

<a>'s
to all match. Please see codepen example below...

http://codepen.io/anon/pen/GovmZa



.container {
width:950px;
margin:0 auto;
}

ul {
display:flex;
align-items: stretch;
justify-content: flex-start;
}

li {
list-style-type:none;
display:flex;
flex-grow:1;
align-items:center;
flex-direction: column;
text-align:center;
border:1px solid #fff;
text-align:center;
}

a {

color:#fff;
padding:10px;
margin-right:1px;
flex: 1;
display: flex;
align-content: center;
align-items: center;
text-align:center;
background-color:#000;
}

<div class="container">
<p>How do I make the links stretch to be equal heights and keep text vertically aligned in the center?</p>
<ul>
<li>
<a href="#">Can</a>
</li>
<li>
<a href="#">somebody please help me figure</a>
</li>
<li>
<a href="#">this</a>
</li>
<li>
<a href="#">out</a>
</li>
</ul>
</div>




Answer

Each list item (li) is already a flex container, but try changing the orientation to column.

Then give the anchors a flex: 1, so they occupy all available space.

li { flex-direction: column; }
a  { flex: 1; }

To keep the text horizontally and vertically centered, add text-align: center to the li and make the anchors flex containers,as well, adding in align-* properties.

li { 
  flex-direction: column;
  text-align: center;
}

a {
  flex: 1;
  display: flex;
  align-content: center; /* will vertically center multi-line text */
  align-items: center;   /* will vertically center single-line text */
}

Revised Codepen