DEV Community

Joefrey Mahusay
Joefrey Mahusay

Posted on

How does rem differ from em in CSS?

In CSS, rem and em are both units of measurement for defining sizes, particularly for font sizes. However, they have different ways of calculating the size based on the context.

You can use this tool plexcalc.com to easily convert px to rem units

em (emphasized):

The em unit is relative to the font-size of its closest parent or the element itself.

If you set the font size of an element using em, it will be a multiple of the parent element's font size.

For example, if the font size of an element is set to 2em, it means the font size is twice the size of its parent's font size.

body {
  font-size: 16px;
}

.example {
  font-size: 2em; /* This would be 32px (2 times the body font size) */
}
Enter fullscreen mode Exit fullscreen mode

rem (root em):

The rem unit is relative to the font-size of the root element (usually the element), regardless of the font size of its nearest parent.
This can be useful for maintaining a consistent size across the entire page, especially when dealing with complex nested structures.

html {
  font-size: 16px;
}

.example {
  font-size: 2rem; /* This would be 32px (2 times the root font size) */
}
Enter fullscreen mode Exit fullscreen mode

Conclusion, while em is relative to the font size of the nearest parent, rem is relative to the font size of the root element. Using rem can make it easier to maintain a consistent and predictable layout across different parts of a webpage.

Top comments (0)