cssfont-size

What's the difference between em units and percents?


I have read a lot of articles on this topic (and searched for Q&A), and I have found, but I still don't understand what the difference between em units and percents is. Help?

P.S. I've seen this code example:

p { font-size: 10px; }
p { line-height: 120%; }  /* 120% of 'font-size' */

What is that supposed to mean? Why on earth would anyone want to set a line height to a percentage value of a font size?


Solution

  • Percentage values are relative to some quantity depending on the context, sometimes to a value from another property of the element or its parent.

    In the context of an element em values are relative to the element's computed font size, except in font-size where they are relative to the parent's computed font size. At the root or outside of an element they are relative to the initial font size, which is usually 16px and may be adjusted for accessibility in the browser's settings.

    Specifically, in these cases there is no difference between them (1em equals 100%):

    Note: It is usually preferred to use unitless numbers in line-height. Since the value inherited by the element's children will not be kept in percentages or em but rather be the computed value which is absolute, the value of line-height inherited in the descendants will not adjust relative to their own font size if the latter is changed.

    Outdated (edited): The answer originally included a caveat that is no longer true in modern browsers. In certain ancient browsers setting the font-size of the first ancestor element to define it (usually body or html) to an em value could produce exaggerated font sizes. You can read about it here, here, and here.