Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Inherit and em-units not rendering properly

Tags:

css

I have some HTML

<ul>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
</ul>

And some css

body {font-size:2em}
li {font-size:60%}
li:nth-child(2){font-size:inherit}

And all is good

enter image description here

If I replace the li font-size with an em unit the inheritance breaks

body {font-size:2em}
li {font-size:1em}
li:nth-child(2){font-size:inherit}

enter image description here

What, o dear gods of css, may cause this?

See fiddle here, http://jsfiddle.net/3ho1uc3u/

like image 866
Eric Herlitz Avatar asked Sep 18 '14 18:09

Eric Herlitz


Video Answer


2 Answers

In CSS, if you give a relative unit, it is by default relative to the size you inherit from. In your case if you use 1em is like you set font-size: 100%.

li {font-size:0.6em}

body {font-size:2em}
li {font-size:0.6em}
li:nth-child(2){font-size:inherit}
<ul>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
  <li>Lorem ipsum</li>
</ul>

EMs do work like percentages in that the base font size is always 1em and .6em would be 60% of that (in the same way 1.2em would be equivalent of 120% of base font size).

like image 184
Alex Char Avatar answered Sep 28 '22 17:09

Alex Char


1em is one unit of the inherited font size.

So if you set 2em on the body, then 1em inherited by the li is actually 2em of the size that body inherited at first place (in your case the default 16px of the browser.)

body           {font-size:2em}
li             {font-size:1em}     /* will be 2em of the inherited size by body*/
li:nth-child(2){font-size:inherit} /* will be 2em of the inherited size by body*/

Both li types will have the same font size.

The first one has 1 unit (or 1em) of the inherited 2em, the second one inherits 2em directly.

like image 24
Arbel Avatar answered Sep 28 '22 18:09

Arbel