Skip to main content
Practice Problems

CSS units: px, rem, em

In CSS, various units of measurement are used to set sizes (margins, fonts, widths, etc.). Among them, especially important are: px, em, rem. They affect responsiveness, scalability and style inheritance.


px β€” pixels

  • Absolute unit of measurement.
  • Sets fixed size, independent of parent or root font.
  • Doesn't adapt to scaling, poorly suited for responsive design.
css
font-size: 16px; padding: 10px 20px;
  • Suitable for pixel-perfect design
  • Scales poorly and doesn't account for user settings

em β€” relative unit

  • Relative to parent element's font size.
  • 1em = current parent's font-size.
  • Used for margins, padding and even font-size, but can behave unpredictably when nested.
css
/* parent */ .parent { font-size: 16px; } /* child */ .child { font-size: 1.5em; /* 24px relative to parent */ }

em nesting can accumulate:

css
.outer { font-size: 16px; } .inner { font-size: 1.2em; /* 16px Γ— 1.2 = 19.2px */ } .inner .text { font-size: 1.2em; /* 19.2px Γ— 1.2 = ~23px */ }

rem β€” root em

  • Relative to root element's (html) font size.
  • 1rem = font-size at <html> level (16px by default).
  • Independent of parent, making rem more predictable.
css
html { font-size: 16px; } .button { font-size: 1.25rem; /* 20px */ padding: 0.5rem 1rem; /* 8px 16px */ }
  • Convenient for responsive typography
  • Works well with media queries
  • Easy to scale (change 1 value in html β€” everything changes)

Comparison Table

UnitRelative to?Scaling SupportApplication
pxAbsolute pixel❌Fixed sizes
emParent font-sizeβœ… (but can accumulate)Internal padding, margin
remhtml font-sizeβœ…Text sizes, layout, everything

When to use what?

  • px β€” when you need to fix size regardless of context (e.g., 1px icon).
  • em β€” for component internal scalability (e.g., padding, margin).
  • rem β€” for global typography, margins, responsive design.

Tip:

Use rem for base sizes, em β€” for component internal proportions, and px β€” only in extreme cases.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems