What’s the difference between rem and em in CSS?

3 min
What’s the difference between rem and em in CSS?

CSS stands for Cascading Style Sheets and this cornerstone technology of the World Wide Web has completely changed the way of websites development. Like always, in any case we can find things that bother on the beginning or are just different and hard to understand. In this short article I’ll try to explain the difference between rem and em units.

EM unit

Em (relative to the font size of the element) is a unit of measure that is based on the font size of the element itself or the nearest parent. Let’s see the following example:

<style type="text/css">
  div.site-body {
    font-size: 15px;
  }
  div.site-body h2 {
    font-size: 1.5em;
  }
</style>

<div class="site-body">
  <h2>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</h2>
</div>

In the above example, the h2 element’s font-size attribute will be 22.5px, because of multiplication by 1.5 of the basic font-size: 15px attribute of the parent’s div with the site-body class. So in this case, 1em is 15px, so 1.5em will be 22.5px (15 x 1.5 = 22.5).

REM unit

Rem (relative font size of the root element) is a similar to em unit, but it has its reference to the major element of the document. The most common DOM element is the html tag. So let’s track the following code:

html {
  font-size: 12px;
}
h2 {
  font-size: 3rem;
}
article {
  font-size: 1.5rem;
}

In this case, the h2 element will be 36px font size (12 x 3 = 36) and text placed in the article element will be covered by the 18px font size (12 x 1.5 = 18).

Conclusion

I hope that in a simple way I was able to explain the use of em and rem units.


Post a Comment

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