Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

html - How to calculate the height of an inline element

I have a span element with the following CSS:

span.test {
  font-size: 20px;
  line-height: 1;
}

Why the calculated height of the span seems to be 22px? Where do these 2 extra pixels come from?

enter image description here

Is it possible to make it tall 20px without using inline-block ?

Here is the simple jsbin I used to test: http://jsbin.com/tigevecemoco/1/edit

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The CSS 2.1 spec says:

10.6.1 Inline, non-replaced elements

The 'height' property does not apply. The height of the content area should be based on the font, but this specification does not specify how.

As it happens the height, as opposed to the line-height, of a non-replaced inline element has very little effect on anything else so browsers are pretty free to report whatever number they like here.

However, a little reverse engineering can be instructive.

If we look at the font metrics for Times New Roman, we see EM size of 2048, WinAscent of 1825, and WinDescent of 443. Sum the ascent and descent, divide by the EM size, multiply by the font size (20px) and round to the integer and we get 22px.

Taking Arial as another font, we have EM size of 2048, WinAscent of 1854, and WinDescent of 434. Do the calculation again and we again get 22px.

What about a different font? Tahoma has EM size of 2048, WinAscent of 2049, and WinDescent of 423. Do the calculation again and this time we get 24px. And hey presto, if you try your JsBin with the Tahoma font, Firefox does indeed show a height of 24px.

The font metrics above were obtained from loading the fonts into Type Light 3.2.

Not conclusive, but a reasonable suggestion of how it all works.

Is it possible to make it tall 20px without using inline-block ?

Assuming the above is correct, you should be able to achieve it by using a custom font and modifying the font metrics of that font to suit. I wouldn't like to predict the knock-on effects of doing that though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...