Félix Sanz
Félix Sanz

Reputation: 1892

Why line-height of code tag is "broken"?

Using this HTML and CSS:

code {
  background-color: grey;
  padding: 2px 7px;
  line-height: 24px; /* this doesn't seem to do anything, but added anyway */
}

p {
  line-height: 24px;
}
<p>test 1</p>
<p>test <code>2</code></p>

The height of the first paragraph is 24px while the height of the second is 25px, even if both have the same line-height and computed line-height value (24px).

If you add line-height: normal; to the <code> tag, the problem is fixed.

Why?

The line-height and computed line-height is the same in both cases. Why different height and why code needs to have line-height:normal? Isn't that the default already?

EDIT: Even if giving line-height: 24px to the <code> tag, that computes a height of 25px anyway.

Upvotes: 4

Views: 158

Answers (1)

Mr Lister
Mr Lister

Reputation: 46579

If you have two different fonts with different metrics in one line, the total height might not be the same height as either of the fonts, even if they have the same height in pixels.

The thing is, the fonts are positioned on the baseline, so if one font has a larger descender (and a smaller ascender), this is what happens:

enter image description here

As you can see, the total height is larger than the black rectangles, even if those rectangles have the same height!

As for the line-height property, remember that this property is inherited.
So if you set a value of 24px on the p, the code also gets the line height of 24. But if you then explicitly reset the value for code to normal, the line height for code is reset to 1.2 times the font size.
So then the line height for code (and therefore the height) is 19 pixels, and it no longer influences the total height of the p.

enter image description here

Upvotes: 3

Related Questions