sun qingyao sun qingyao - 1 month ago 7
CSS Question

is line-height:1 equivalent to 100%?

Please take a look at the following snippets first:



body {
line-height: 1;
}

<h1>
Hello <br> world
</h1>







body {
line-height: 100%;
}

<h1>
Hello <br> world
</h1>





The upper one uses
line-height: 1;
, while the lower one uses
line-height: 100%;
. I thought they must be identical, and MDN seems to agree with me:


<number>


The used value is this unitless
<number>
multiplied by the element's
font size. The computed value is the same as the specified
<number>
.
In most cases this is the preferred way to set line-height with no
unexpected results in case of inheritance.

<percentage>


Relative to the font size of the element itself. The computed value is
this percentage multiplied by the element's computed font size.

Percentage and em values may have unexpected results, see "Notes" section.


and in the "Notes" section:


It is often more convenient to set
line-height
by using the
font

shortcut as stated in the "Examples" section above.


However, actually, they are different!

My question is: Why are they different, and should I prefer
<number>
as suggested by MDN?




I'm using Safari Version 10.0.1 (12602.2.14.0.7).

Answer

The real reason is that the way they work is different and it can be understood by having a look at the below statement from the W3C Spec: (emphasis is mine)

When a numerical value is specified, the line height is given by the font size of the current element multiplied with the numerical value. This differs from a percentage value in the way it inherits: when a numerical value is specified, child elements will inherit the factor itself, not the resultant value (as is the case with percentage and other units).

When unitless value (numerical value) is specified, the element inherits the factor which is 1 and then multiples it by the h1 element's font-size (which is 2em = 32px) and therefore becomes 32px. For the percentage, the line-height value is calculated and set at body (whose font-size is 16px) and then the h1 inherits the 16px as line-height (instead of 32px).


Summary - in the first snippet (unitless) each element sets its own line-height by multiplying it's own font size (computed/explicitly set) with the factor that is set on the parent whereas in the second, the line height is calculated, set at body and then the resultant value is inherited by the children.

If we set the line-height: 100% directly at h1 then we can see that the outputs match because now the h1 calculates its own line-height as 100% of 2em (or 32px) which is same as 1 * its font-size.

h1 {
  line-height: 100%;
}
<h1>
  Hello <br> world
</h1>