tezvyn:

Relative CSS Units: rem vs. em

AI-drafted, machine-checkedSource: developer.mozilla.orgintermediate
Relative CSS Units: rem vs. em

Relative CSS units like `rem` and `em` tie element sizes to font size for scalable UIs. `rem` is relative to the root font size, providing consistency. `em` is relative to the parent, causing sizes to compound. The footgun is accidentally nesting `em` units.

WHY IT EXISTS: Hardcoding UI dimensions with absolute units like pixels (px) creates rigid designs. When a user increases their browser's default font size for accessibility, a pixel-based layout doesn't adapt, leading to broken UIs and poor readability. Relative units were created to build fluid layouts that respect user preferences.

THE MENTAL MODEL: Think of rem as a global sizing variable and em as a local one. rem (root em) bases its size on one single source of truth: the root <html> element's font size. em bases its size on its immediate parent's font size. This makes rem predictable and em contextual.

HOW IT WORKS: The browser calculates the final pixel value of a relative unit. For rem, it multiplies the value by the root element's font size (e.g., 2rem with a 16px root font becomes 32px). For em, it multiplies the value by the computed font size of the element's direct parent. If that parent also uses em, the calculation compounds. For example, a child with font-size: 0.8em inside a parent with font-size: 0.8em will have a final font size of 0.64 times its grandparent's font size.

WHEN TO USE IT: Use rem for most of your sizing needs: global typography, margins, padding, and layout dimensions. This ensures consistency and simplifies maintenance. Use em sparingly for properties on a component that should scale relative to that component's own font size, such as the padding on a button or the size of an icon next to text.

WHEN NOT TO USE IT: Avoid using em for spacing and layout in deeply nested components. The compounding effect makes sizes difficult to predict and debug. If you find yourself calculating 1 / 1.2 * 0.8 to figure out a font size, you should probably be using rem instead. For elements that must be a fixed size, like a 1px border, px is still the correct choice.

ONE CANONICAL EXAMPLE: Assume the browser default font-size is 16px. If you set div { font-size: 1.25rem; }, that div's font size becomes 20px (1.25 * 16). If a inside that div has font-size: 0.8em, its font size will be 16px (0.8 * 20). If that same instead had font-size: 0.8rem, its font size would be 12.8px (0.8 * 16), ignoring its parent's size completely.

Read the original → developer.mozilla.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.