CodePark/ questions / Responsive design & units
START PRACTICINGPRACTICE
Frontend question · CSS & HTML › Responsive design & units

Compare px, rem, em, % and vw. When would you use each?

Each unit is relative to something different:

  • px is a fixed CSS pixel. It is fine for borders and small details.
  • rem is relative to the root (html) font size. So it respects the user's browser font setting. It is the usual choice for font sizes and spacing.
  • em is relative to the element's own font size. When used in font-size, it uses the parent's font size. It suits things that should scale with the nearby text, like button padding or icon size. But nested em font sizes compound: 1.2em inside 1.2em gives 1.44 times the size.
  • % is relative to the containing block, which is usually the parent. width: 50% uses the containing block's width, and height: 50% uses its height. Padding and margin percentages always use the width, even for top and bottom.
  • vw and vh are 1% of the viewport's width and height. The viewport is the visible browser window. They are useful for full-screen sections and fluid text with clamp(). But vw alone ignores the user's font settings.

On mobile, 100vh can be taller than the visible area, because browser toolbars cover part of the screen. The newer units dvh (dynamic), svh (small) and lvh (large) solve this.

  • rem respects the user's font size, so it is a good default for text and spacing.
  • em scales with the local font size, and nested em font sizes compound.
  • % uses the containing block: its width for width and its height for height. Padding and margin percentages always use the width.
  • vw and vh are viewport units. dvh and svh fix the mobile toolbar problem.