Daily Tips & Tricks for Web Enthusiasts

Smart Line Height

The line-height property has some unexpected inheritance behavior when used with a length or percentage. Take this CSS, for example:

div.example {
    font-size: 20px;
    line-height: 1.5em;
}

div.example h2 {
    font-size: 40px;
}

With this CSS you might expect the line height of h2 elements inside div.example elements to be 60px, but that’s not the case. No, with this CSS, everything inside div.example elements will get the same 30px of line height regardless of their own font size, including those h2 elements.

Why is this? When you provide a length or percentage value for the line-height property the line-height calculation is made at that point, and that calculated value is used going forward. The em unit specifies a length, so we get the 30px of line height calculated immediately and used everywhere.

The good news is that there’s an easy way around this problem: Never provide a length or percentage value when using line-height. Instead use a number with no unit, like this:

div.example {
    font-size: 20px;
    line-height: 1.5;
}

div.example h2 {
    font-size: 40px;
}

Now the line height will be calculated by multiplying the font size of whichever element the line height is being applied to. This results in 30px of line height inside div.example elements by default, and 60px of line height on the h2 elements inside them, just as expected.