🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Know your size – CSS Units Explained: Part 2 REMs and EMs

You can see here the first part of this article: CSS Units Explained: Part 1 pixels, percentages and viewpoints units.

In CSS REM comes to the Root EM, where EM is a term borrowed from the typography world. It refers to a unit that allows setting the font-size of an element relative to the font-size of its parent 🀯.

Anyways, I promise that things will easier after we see these concepts in code.

Let's start with REM, the Root EM. How it works is that you define a font size for the body, and that font-size becomes the base unit of measure:

body { font-size: 18px; }
p {line-height: 2rem; } /* 36px */
h1 {margin-bottom: 3rem; } /* 54px */
.hero {border: 1px solid 0.5rem} /* 9px */

It's quite nice because if we move to a smaller screen it's enough to update just the font-size of the body all changes. All is relative to the base font-size.

On the other size, EM it's relative to the font-size of the parent container. Let's take the following code:

.grid { font-size: 20px; } 
.grid .grid-cell { font-size: 1.5em; }
/* the .grid-cell will have a font-size of 20px * 1.5 = 30px; */

But there is a small gotcha with this em. If em units are used on other properties than font-size, then the value is relative to the element’s own font-size.

So, let's take again the previous code, and add a line-height prop:

.grid { font-size: 20px; } 
.grid .grid-cell { 
    font-size: 1.5em; /* 30px */ 
    line-height: 2em;
    /* WARNING: the line-height will be 30px * 2 = 60px */
}

Another gotcha with em is the cascading effect. If we have this CSS:

.container { font-size: 10px; } 
.child { font-size: 2em; }

We can run into strange situations if we have some markup like this one:

<div class="container"> 
    I'm 10px; all good
    <div class="child"> 
        I'm 20px, as expected 
        <div class="child"> 
            I'm 40px, kind of big 
            <div class="child"> 
                I'm 80px, too big! 
                <!-- and getting bigger -->
            </div>
        </div>
    </div> 
</div>

A great place to use rem or em are as alternatives for pixels in font sizes.

There are cases were used with care em can provide us with a lot of flexibility and fluency. But, to be honest, overall I prefer REM for its predictability and consistency πŸ™‚

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *