CPCODELAB
CSS

CSS Units: px, em, rem, %, vw, vh

9 min read

Absolute and Relative Units

Choosing the right unit is one of the most consequential decisions in CSS. The wrong unit can make your layout break on different screen sizes or user font-size preferences.

  • px — absolute pixel. Good for borders and fine details, but doesn't scale with user preferences.
  • em — relative to the element's own font-size. Useful for padding and margins that should scale with text.
  • rem — relative to the root (<html>) font-size (typically 16px). Best for font sizes and spacing across the page.
  • % — relative to the parent's value of the same property. Commonly used for widths.
  • vw / vh — 1% of the viewport width or height. Perfect for full-screen sections.
css
html {
  font-size: 16px; /* 1rem = 16px */
}

.container {
  width: 90%;        /* 90% of the parent's width */
  max-width: 1200px; /* hard cap in px */
  margin: 0 auto;
}

.hero {
  min-height: 100vh; /* full viewport height */
  padding: 2rem;     /* 32px based on root font-size */
}

.card-title {
  font-size: 1.25rem; /* scales with user preference */
  padding: 0.75em;    /* scales with THIS element's font-size */
}

Use rem for font sizes and global spacing. Use em for component-internal spacing that should scale with the component's own text.

Ready to test yourself?
Practice CSS— quiz & coding exercises