Sobes.tech
Middle+

What is the difference between rem and em?

sobes.tech AI

Answer from AI

rem and em are relative units of measurement in CSS, used for setting sizes but differ in their reference base.

  • em is a relative unit based on the font size of the parent element. For example, if the parent has font-size: 16px, then 1em = 16px. If a child element has font-size: 1.5em, its size will be 24px.

  • rem is a relative unit based on the font size of the root element (usually <html>). For example, if <html> has font-size: 16px, then 1rem always equals 16px, regardless of nesting.

Main difference:

  • em depends on the context (parent), which can lead to cascading multiplication of sizes in nested elements.
  • rem is always fixed relative to the root, simplifying size management and making it more predictable.

Example:

html {
  font-size: 16px;
}

.parent {
  font-size: 20px; /* 1em = 20px inside .parent */
}

.child-em {
  font-size: 1.5em; /* 1.5 * 20px = 30px */
}

.child-rem {
  font-size: 1.5rem; /* 1.5 * 16px = 24px */
}

Use rem for global sizes to avoid unexpected changes, and em when you need to scale relative to the local context.

What is the difference between rem and em? — Frontend - sobes.tech