If vertical aligning seems broken look at line height

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the CSS-and-design category.

Last Updated: 2021-05-16

Imagine you have this style:

.el {
  line-height: 58px;
}

What does this do?

The line-height property is essentially setting a 29px (29 + 29 = 58) text line above and below your text. I.e. it has the effect of centering your text within a space.

Watch out for line height scaling badly with font-sizes

Imagine you had this css:

body {
  font-size; 16px;
  line-height: 120%;
}

h1 {
  font-size: 40px;
}

and this HTML:;

<body>
   <!--Key part: h1 is nested in body-->
  <h1></h1>
</body>

This would look weird in h1 because line-height on body is 16px x 120% = 19.2px. But the h1 inherits this value — i.e. 19.2px, and this is WAY too small for the 40px font-size. I.e. The line height did not scale so now it is too tight.

One way to avoid this is by using the number value for line-heights intead of percentage:

body {
   line-height: 1.5;
}

Now it scales to inherited elements.

References