Units & Sizing

Every width, font-size, and margin you write needs a unit. CSS gives you several, and picking the right one for the job is the difference between a layout that holds together and one that quietly breaks the moment content changes.

Pixels: the fixed unit

px is an absolute unit — a box set to 200px is 200px wide no matter what else is going on around it. That predictability is useful, but it's also the problem: a pixel value never adapts to the text size the visitor has chosen or the screen they're using.

Try it yourself
Result

Pixels are a reasonable choice for things that genuinely shouldn't scale — a 1px border, a 2px focus ring — but using them for every width and font-size on a page is what makes layouts feel rigid.

Percentages: relative to the parent

% sizes an element relative to its containing element. A child at width: 50% is always half of whatever its parent measures, so it resizes automatically when the parent does:

Try it yourself
Result

Change .parent's width and the child's width follows along, since 50% is only ever meaningful relative to the box that contains it.

em and rem: relative to text size

em is relative to the font-size of the element it's used on — which makes it handy for things like padding that should scale alongside text, but it compounds when elements are nested, because each element's em is based on its parent's already-scaled size. rem sidesteps that entirely: it's always relative to the font-size set on the root <html> element, no matter how deeply nested the element is.

Try it yourself
Result

Try nesting a second .inner-em inside the first one and you'll see the size keep climbing — 1.5em of 1.5em of 20px. That compounding is exactly why most style guides default to rem for font sizes and reserve em for the occasional case where scaling with the local element is actually what you want, like an icon that should grow with its own button's text.

vw and vh: relative to the viewport

vw and vh are percentages of the browser's viewport — 1vw is 1% of the viewport width, 1vh is 1% of its height. They're useful for elements that should genuinely track the size of the screen, like a hero section that always fills the visible height:

Try it yourself
Result

Notice the distinction from percentages: % looks at the parent element, vw/vh look straight past every ancestor to the browser window itself. That's exactly why they're the wrong tool for most everyday layout — you usually want an element to respond to the box it lives in, not the whole screen.

Rule of thumb: rem for font sizes and spacing that should scale with the user's text preferences, % for widths that should track a parent container, vw/vh for the rare element that truly needs to reference the viewport itself, and px for small fixed details like borders where scaling would look wrong.