htmlcssfont-size

Why is 1em shorter than the default font size?


I was doing some experiments, and then I ran into this issue. I sat a div's height to 1em, and I expected the div to contain the whole height of the text within, but it did not. 1em is my browser is 16px.

When I did not specify the div's height, it successfully contained the whole height of the text, and when inspected, it turned to be of height 19px.

Is my understanding of em wrong, as I thought it should represent the default font height of the browser.

div {
  margin: 0;
  padding: 0;
}
.first {
  height: 1em;
  background: green;
}
.second {
  background: orange;
}
<div class="first">سلامًا Say I Wantأًّ</div>
<br />
<div class="second">سلامًا Say I Wantأًّ</div>

https://jsfiddle.net/9t43kyu2/1/


Solution

  • The typographical line-height of text isn't exactly the actual height of the rendered text in pixels:

    image

    The line-height CSS parameter of a text contains only the height between "caps height" and the "baseline". In my experience, it is in most cases 1em, but also on most non-standard sources of the net. However, its standardized details are better described in @web-tiki 's answer.

    If characters which have parts over it or below it are present, they will result in text whose height (in pixels) is bigger as the line height (in pixels).

    The text can have small details which are below or over the standard text line. For example, the lowest part of a y, or the highest parts of a non-ASCII Ű character. These cause continuous problems in the positioning.

    If you don't set the div height, it will be by default auto, which mean, the whole content will be in it. If you specify the div height to the actual line size, without padding, border and margin, then some pixel of your text will maybe overflow. You only didn't see it, because the default value of the overflow CSS-parameter is visible.

    Best test for that: create a div with the following settings:

    #divId {
      height: 1em;
      line-height: 1em;
      overflow: hidden;
    }
    

    ...and copy-paste a into its content (but characters are also okay). You will see it clipped on both sides.