CSS3
CSS3

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

Every size in CSS needs a unit, and picking the right one matters more than it seems. px (pixels) is an absolute, fixed unit 20px is always exactly 20px, regardless of anything else, great for borders or small precise details. % (percent) is relative to the PARENT element's size width: 50% means half of whatever the parent's width happens to be, perfect for flexible, responsive layouts. em is relative to the font-size of the CURRENT element (or its parent, if not set) 2em means 'twice the current text size', which is why it's popular for padding around text. rem is similar to em, but always relative to the ROOT element's font-size (usually the <html> tag), making it far more predictable across nested components most modern projects prefer rem over em for this reason. vh and vw are relative to the VIEWPORT the visible browser window itself: 100vh means 'exactly the full height of the screen', ideal for a hero section that always fills the visible area regardless of screen size.

Why this matters

  • ·rem keeps sizing predictable and consistent no matter how deeply nested an element is
  • ·% and viewport units (vh/vw) create layouts that automatically adapt to different screen sizes
  • ·px gives pixel-perfect precision when you need exact, unchanging sizes

Common mistakes

  • ·Using em everywhere can cause sizes to unexpectedly compound when elements are nested inside each other
  • ·Relying only on px for everything makes a design harder to scale for accessibility (users who increase browser font size)
  • ·100vh can behave unexpectedly on some mobile browsers due to dynamic address bars
Your code
Live preview

Frequently asked questions

em is relative to the current element's own font-size (which can compound when nested); rem is always relative to the root <html> font-size, making it more predictable.

Practice questions

Question 1

Make a box with width: 60% and padding: 2rem, using the internal method.

Your code
Live preview

Question 2

Make a div exactly fill the visible screen height using vh.

Your code
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 10

Which unit is fixed and never scales with anything else?