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 of1emscales with the text.rem: a multiple of the root (html) font size, which defaults to 16px. So1rem= 16px and1.5rem= 24px. Unlikeemit never compounds through nesting, which is whyremis the go-to unit for font sizes and spacing.vw/vh: 1% of the viewport (the browser window) width or height.100vhis 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 says | you write | why |
|---|---|---|
| h1 is 40px | font-size: 2.5rem | 40 ÷ 16 = 2.5; scales if the user raises their base size |
| card padding 24px | padding: 1.5rem | spacing tracks the text size |
| hairline divider 1px | border: 1px solid gray | must stay one device pixel — px is correct here |
| content column 960px | width: 90%; max-width: 60rem | fluid on phones, capped on monitors |
| full-screen intro | min-height: 100vh | one 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?