Course outline · 0% complete

0/30 lessons0%

Course overview →

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

lesson 5-3 · ~8 min · 16/30

Absolute and relative units

A stylesheet written only in px breaks the moment anything resizes: users raise their default font size (a common accessibility setting), phones vary in width, and text zooms. Relative units exist so one set of styles survives all of that, and choosing the right unit is a real, daily decision on working teams.

  • px: CSS pixels. Fixed. Fine for borders, small gaps, and max-widths.
  • %: a percentage of the parent's size. width: 50% is half the parent's width.
  • em: a multiple of the current element's font size. Padding of 1em scales with the text.
  • rem: a multiple of the root (html) font size, which defaults to 16px. So 1rem = 16px and 1.5rem = 24px. Unlike em it never compounds through nesting, which is why rem is the go-to unit for font sizes and spacing.
  • vw / vh: 1% of the viewport (the browser window) width or height. 100vh is exactly one screen tall, a favorite for hero sections — the full-screen opening banner at the top of a landing page, holding the big headline and main button. (You will build one in the capstone.)

Rule of thumb: text in rem, layout widths in % with a max-width, full-screen sections in vh, hairlines in px.

Quiz

The root font size is the default 16px. How many pixels is 2.5rem?

Worked example: converting a mockup

A designer hands you a mockup measured in pixels. Here is how a working stylesheet translates it, using the rule of thumb above:

mockup saysyou writewhy
h1 is 40pxfont-size: 2.5rem40 ÷ 16 = 2.5; scales if the user raises their base size
card padding 24pxpadding: 1.5remspacing tracks the text size
hairline divider 1pxborder: 1px solid graymust stay one device pixel — px is correct here
content column 960pxwidth: 90%; max-width: 60remfluid on phones, capped on monitors
full-screen intromin-height: 100vhone viewport tall on any device

The point of the conversion: the numbers stop being frozen. A user who sets their browser font to 20px gets an h1 of 50px and padding of 30px automatically, and nothing overlaps.

Quiz

A card sets font-size: 20px. A paragraph inside it inherits that size and declares padding: 1em. How much padding does the paragraph get?

Code exercise · javascript

Write both conversion helpers: remToPx(rem, rootSize) and pxToRem(px, rootSize). They are one multiplication and one division.

Problem

Which unit equals 1% of the browser window's height?