DEV Community

Mạnh Đạt
Mạnh Đạt

Posted on

Guide to line-height in CSS

line-height is an interesting CSS property. This is usually used to set the distance between lines of text.

We are going to use this HTML for this post:

<body>
<h1>hello</h1>
</body>
Enter fullscreen mode Exit fullscreen mode

What does line-height mean?

If I set the following rule:

h1 { line-height: 40px; }
Enter fullscreen mode Exit fullscreen mode

When inspecting that h1 element in dev tools, I can see where is that 40px:
Alt Text

Ways to specify line-height

You can specify line-height with or without unit. With that said, writing either:

line-height: 1.2;
Enter fullscreen mode Exit fullscreen mode
line-height: 1.2em;
Enter fullscreen mode Exit fullscreen mode

is valid.

When your element has line-height rule, it will be calculated based on that element's font size.

So, these three blocks produce identical results:

h1 {
    font-size: 20px;
    line-height: 2;
}

Enter fullscreen mode Exit fullscreen mode
h1 {
    font-size: 20px;
    line-height: 2em;
}

Enter fullscreen mode Exit fullscreen mode
h1 {
    font-size: 20px;
    line-height: 200%;
}

Enter fullscreen mode Exit fullscreen mode

The difference between specifying unit and not specifying unit

Take a look at these pieces of code:

Code 1:

body {
    font-size: 10px;
    line-height: 1.5em;
}

h1 {
    font-size: 30px;
}

Enter fullscreen mode Exit fullscreen mode

Code 2:

body {
    font-size: 10px;
    line-height: 1.5;
}

h1 {
    font-size: 30px;
}

Enter fullscreen mode Exit fullscreen mode

In case you don't see the difference, in the first block, I declared line-height for body with em while in the second, line-height doesn't have an unit.

What's the difference in h1's line height?

Can you guess?

  • In the first case, h1's line-height would be 15px
  • In the second case, h1's line-height is 45px

Huge difference, but why?

First of all, line-height is inherited. Since h1 doesn't have a rule for line-height so it inherits that property from its parent. In this case, that parent is body.

In the first case, as I specified the unit, the value is computed to 15px and this value is passed down to h1.

In the second case, I didn't specify an unit, so h1 inherit a value without unit. Thus, it will use this value to multiple with its font size to calculate line-height.

Since h1's font-size is 30px, 30 * 1.5 = 45.

Hope you find this post interesting :)

Top comments (0)