Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to TRULY vertically center text with flexbox?

So vertically centering text seemed simple enough with justify-content and align-items center but when I looked closely I can see that the text isn't truly centered. It has less spacing at the top of the character. I tried to investigate further by searching online and I found this https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align but there must be a simpler solution to this.

Example https://jsfiddle.net/z7cy487o/

html,
body {
  height: 100%;
}

.box {
  height: 10%;
  width: 400px;
  background: #000;
  font-size: 11vh;
  color: #FFF;
  text-align: center;
  padding: 0 20px;
  margin: 20px;
  display: flex;
  justify-content: center; /* align horizontal */
  align-items: center;     /* align vertical */
}
<div class="box">
  C
</div>
like image 334
Daniel Kobe Avatar asked Oct 18 '22 10:10

Daniel Kobe


1 Answers

The way you perceive that depends on which characters you are using. I copied your example twice to show different situations:

In the second version I only used the letter "y", which has a descender, i.e. a part that extends below the baseline, to the lower border of the area which is defined as line-height. On the other hand, it doesn't go up the whole way, so it seems exactly the opposite of the first version (letter "C") concerning vertical alignment.

In the third version I used both of those letters combined in a word. Here you can see that the different characters/letters together indeed do extend across the whole width, so the vertical centering is correct as it is.

Line-height (and in relation to that, vertical alignment of letters) does not depend on which letters are used - it always applies to all possible letters/characters, even if they are not used in that particular situation.

html, body { height: 100%; }
.box
{
    height: 10%;
    width: 400px;
    background: #000;
    font-size: 11vh;
    color: #FFF;
    text-align: center;
    padding: 0 20px;
    margin: 20px;
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center; /* align vertical */
}
<div class="box">
C
</div>

<div class="box">
y
</div>

<div class="box">
Cyborg
</div>
like image 178
Johannes Avatar answered Nov 01 '22 14:11

Johannes