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>
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
The li's were all the same height, it's the anchor tags within the li's that are the issue.
Apply some flex styling to those and it'll fix your problem
.container {
width:300px;
margin:0 auto;
}
ul {
display:flex;
justify-content: flex-start;
}
li {
list-style-type:none;
display:flex;
align-items: stretch;
flex-grow:1;
}
a {
display:flex;
align-items: center;
background-color:#000;
color:#fff;
padding:10px;
align-content: center;
margin-right:1px;
}
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With