What's the difference between CSS “em” and “rem”?

2 points by Hippoly ↗ HN
I've read this much about this:

1) Learning Web Design Book by Jennifer Niederst Robbins

1 rem= 1* browser's default font size

1 em= depends on the element type, for h1 it's something, for h2, it's sth else.

2) https://css-tricks.com/confused-rem-em/

>While em is relative to the font-size of its direct or nearest parent, rem is only relative to the html (root) font-size.

I get the rem part, but not the em part. What does it mean?

3) https://blog.logrocket.com/using-em-vs-rem-css/#:~:text=Let%27s%20get%20started!-,What%20are%20em%20and%20rem%20and%20why%20use%20them%3F,relative%20to%20a%20set%20value.

I've read this as well but since I'm only knowing html and starting to learn css, I could not get most of the things written there.

4) https://www.youtube.com/watch?v=tlRLEsZa89M

I watch this short video. It does makes things somewhat clear about "inherits from parent".

Anyway, I am eager to learn the crux of "em". Maybe with some code examples, or figures(if it's lying anywhere in internet)

2 comments

[ 4.3 ms ] story [ 18.1 ms ] thread
An example might be helpful. Imagine you had buttons that come in small, medium, and large sizes. You want those buttons to have similar, proportional padding, letter-spacing, and border-radius. Margin around the buttons, however, should always be the same size to align with your columns or something.

You can put those properties which should vary in ems and then all you have to do is change the large and small font sizes from the default. Margin, however, remains in rems because it needs to be consistent. Everything will scale proportionately and your large and small button classes are clear, expressive, and concise.

https://codepen.io/LukeAtWork/pen/gOzNdRo

Think of `em` like a percentage of the current font size. So if you have a `div` with a font size of 16px, then a `p` tag within that with a font size of `1em` will be 16px. If the `p` tag is `0.8em`, then the font size will be 12.8px (or 80% of the current font size).

  + html = 16px
    |
    + div = 1rem (equivalent to 16px)
      |
      + p = 0.8em (equivalent to 80% of 1rem, or 16 \* 0.8, or 12.8px)
        |
        + small = 0.8em (equivalent to 80% of 0.8em, or 12.8 \* 0.8, or 10.24px)
        + span = 0.8rem (equivalent to 80% of 1rem, or 16 \* 0.8, or 12.8px)
So by changing the font size of your `div`, all child elements that use `em` will automatically re-render as well (but child elements using `rem` won't resize, because their size isn't affected unless the `html` font size is changed).

The "current font size" is determined by lookup up the hierarchy to the nearest parent element with a specified font size, ending with the `html` element which will reflect the browser's default font size if nothing else has been set.