CSS: REMs vs EMs

So you’ve been using pixels (px) for your font sizes since you first learned CSS, but you’ve been hearing about REM and EM units and how they should be used for today’s websites instead of pixels. Before I try to explain how they work, what exactly are they? An EM is a CSS unit mainly used today for font sizes. A REM is a root EM (this is explained more later).

The first thing to note is that the default font size in most web browsers today is 16px. EMs and REMs lets developers scale elements up and down, which is very useful for responsive design (mobile and small screens vs large screens) and accessibility. The web browser converts the EMs/REMs into pixel values.

How do REMs work?

REM units look at the font size of the root element of the page, which is the html element (remember it’s 16px by default usually), and they take that size and multiply it by the REM value you set.

So in the below REMs example, the “text-1” class is set to use 1.5rem and that will be multiplied by 16, which equals 24, so the font size will be 24px. Make sense?

REMs example

/*CSS*/
.text-1 {
  font-size: 1.5rem;
}

/*HTML*/
<html>
  <body>
    <p class="text-1">Testing text 1.</p>
  </body>
</html>

How do EMs work?

EM units look at the font size of its parent and they take that size and multiply it by the EM value you set.

So in the below EMs example, the “text-2” class is set to use 1.5em and that will be multiplied by the font size of its parent (“text-2″‘s parent is the body element and the body’s font size is 12), so it will be 1.5 x 12, which equals 18, so the font size will be 18px. Make sense?

EMs example

/*CSS*/
body {
  font-size: 12px;
}
.text-2 {
  font-size: 1.5em;
}

/*HTML*/
<html>
  <body>
    <p class="text-2">Testing text 2.</p>
  </body>
</html>

If you have any questions feel free to leave a comment and ask. Also, if you found my explanation confusing or if you learn better with video, I recommend checking out the below helpful video by YouTuber Coder Coder where she goes over using REMs instead of pixels.

px vs rem: what to use for font-size in your CSS

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.