Absolute vs Relative CSS Units (px, em, rem, %)

Absolute Units: px

A pixel (px) is a fixed unit - 16px is always 16px, regardless of any parent element or user setting. It is predictable, but it does not automatically scale if a user increases their browser's default font size for accessibility.

Relative Units: em, rem and %

UnitRelative to
emThe font size of the current element (or its parent, for non-font properties)
remThe font size of the root <html> element - stays consistent no matter how deeply nested
%Usually the parent's corresponding size (width, height, font-size, etc.)

Why em Can Compound Unexpectedly

.parent { font-size: 20px; }
.child { font-size: 1.5em; }  /* 30px */
.grandchild { font-size: 1.5em; } /* 45px, relative to .child's 30px */

Because em multiplies against its parent's font size, nesting several elements that each use em can cause sizes to grow or shrink faster than expected. rem avoids this by always referring back to the root font size instead of a parent.

Choosing Between Them

  • Use rem for font sizes and spacing - predictable and easy to scale globally by changing the root font size.
  • Use % for widths inside a fluid layout.
  • Use px for things that genuinely should never scale, like a 1px border.
  • Use em sparingly, mainly when a value should scale with its own element's font size, such as padding inside a button that should grow with its text.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.