Marlon Marlon - 1 month ago 6
CSS Question

Center align text inside a element in a flex row

I have the following html:

<div class="toolbar">
<span>My title</span>
<a href="#">User Name</a>
<a href="#">
<img src="http://image.flaticon.com/icons/png/128/56/56805.png" />
</a>
</div>


I've used flex box to make the two links to align right and the "My title" text to fill the remaing space, as show in this example: https://jsfiddle.net/tz472j3o/

What I need now is to center both the text and image link vertically in the toolbar. I know i could do this with
align-items: center
, but this won`t work for me because i need to change the background color of the link on mouse hover, so I need the link height to take all vertical space in the toolbar.

So, what i need is the a element to stretch vertically to take all available space, but to center its text vertically inside it.

Answer

Make the link display:flex and align-items:center.

.toolbar {
  background-color: lightblue;
  height: 40px;
  display: flex;
}
span {
  flex-grow: 1;
  align-self: center;
}
a {
  margin-left: 5px;
  display: flex;
  align-items: center;
}
a:hover {
  background-color: white;
}
img {
  width: 20px;
}
<div class="toolbar">
  <span>My title</span>
  <a href="#">User Name</a>
  <a href="#">
    <img src="http://image.flaticon.com/icons/png/128/56/56805.png" />
  </a>
</div>