Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between em units and percents?

Tags:

css

font-size

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?

like image 414
Or'el Avatar asked Sep 02 '25 06:09

Or'el


1 Answers

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%):

  • In line-height both units are relative to the element's computed font size.

  • In font-size both units are relative to the parent's computed font size, and at the root to the initial value.

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.

like image 159
4 revs, 3 users 79%orelby Avatar answered Sep 04 '25 22:09

4 revs, 3 users 79%orelby



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!