Difference Between Em And Rem Units In CSS

We will see the difference between em and rem units in css.

Let’s understand both of them in detail.

1. em Unit:

The em unit allows setting an element’s font size relative to its parent’s font size. When the size of the parent element changes, the child’s size changes automatically.

When em units are used on the font-size property, the size is relative to the parent’s font size. When used on other properties, it’s relative to the font size of that element itself. Here, only the first declaration takes the reference of the parent.

– The font-size of the .child element will be 40px (2*20px).
– The margin of .child will be 60px. That’s 1.5 times the font-size of our element (1.5*40px).

Let’s see the example.

First of all, Create HTML in the index.html file.

<body>
  <div class="parent-div">
        This is parent
        <div class="child-em-div">
            This is Child in em unit system
        </div>
    </div>
</body>

Now add CSS in <style>…</style> tag in index.html file.

<style>
  .parent-div {
        font-size: 20px;
    }
 
    .child-em-div {
        font-size: 2em;
        margin: 1.5em;
    }
</style>
Output:

2. rem Unit:

The rem is based upon the font-size value of the root element, which is the <html> element. And if the <html> element doesn’t have a specified font-size, the browser default value of 16px is used. So here only the value of the root is considered, and there is no relation with a parent element.

– The font-size of the .child element will be 60px (2*30px).
– The margin of .child will be 45px. That’s 1.5 times the font-size of the html element (1.5*30px).

Let’s see the example.

First of all, Create HTML in the index.html file.

<body>
  <div class="parent-div">
        This is parent
        <div class="child-rem-div">
            This is Child in em unit system
        </div>
    </div>
</body>

Now add CSS in <style>…</style> tag in index.html file.

html {
   font-size: 30px;
}
.parent-div {
   font-size: 20px;
}
.child-rem-div {
   font-size: 2rem;
   margin: 1.5rem;
}
Output:

Hope you got a clear difference between the em and the rem units

Submit a Comment

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

Subscribe

Select Categories