问题
I saw people using line height without specifying a unit, like this: line-height: 1.5;
What does the number represents? I'm guessing it's a ratio so is it like em
?
回答1:
line-height@ Mozilla Developer Network has a very good explanation (and examples) which is a easier to understand compared to the line-heightCSS specification.
line-height
can have the value specified in one of the following ways
line-height: normal | <number> | <length> | <percentage>
In your case, you are using a <number>
which is described as:
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.
回答2:
Yes, it is a ratio: 1.5 means 1.5 times the font size of the element. So it means the same as 1.5em or 150%, but with one important exception: in inheritance, when a pure number is used, the number is inherited, not the computed value.
So if you have an element with font size 24pt, line-height: 1.5
sets the line height to 36pt. But if the element has a child, i.e. an inner element, with font size of 10pt, and without any line height set on it, then the child inherits the line-height
value of 1.5, which means 15pt for that element. If, on the other hand, the line height were set to 1.5em
or 150%
, then the child would inherit the computed value of 36pt, creating grotesque line spacing.
Technically, this is hidden under a formulation that says. for a pure number used as line-height
value: “The computed value is the same as the specified value.” So, nominally, the child inherits the “computed” value of 1.5, which will then be interpreted in the context of the child (1.5 times its font size).
回答3:
See the respective spec @W3C:
The used value of the property is this number multiplied by the element's font size. Negative values are illegal. The computed value is the same as the specified value.
So as you guessed it is a ratio and relates to the current font-size
.
回答4:
line-height: X;
basically translates to line-height: (X*100)%;
line-height: 1;
is the same as line-height: 100%;
Similarly,
line-height: 1.5;
is the same as line-height: 150%;
Where line-height: X%;
means X% of the line-height of the currently set font and size for the element.
For example, if the line-height for an element as per the current set font and size is 24px
, line-height: 150%
would make its line-height 36px
. And so on..
回答5:
You can also use rem in order to to use the root em size instead of the current font size.
So these are both line height of twice the current font-size
font-size: 2em;
font-size: 2;
But this is a line height of twice the ROOT font size
font-size: 2rem;
来源:https://stackoverflow.com/questions/12303169/line-height-without-units