em vs rem in css

em is relative to the font-size of the parent element.
rem is relative to the font-size of the root(html) element.

By default, in most of the browsers, 1em is 16px if font-size is not set on any of the parent elements.

When em is used to set any other property other than font-size, it is relative to the elements font-size.


Ex:

html{

  font-size: 15px;

}

.parent {

    font-size: 20px;

}

.child {
 
    font-size: 2em;  /* 40px will be the font-size */
    padding: 1.5em; /* 60px(1.5 * 40) will be the padding */

}

.child1{

  font-size: 2rem; /* 30 px will be the font size */
  padding: 1.5rem; /* 45 px will be the padding */

}


Sources:

https://alligator.io/css/rem-vs-em-units/

https://developer.mozilla.org/en-US/docs/Web/CSS/font-size#relative-size

Comments