CSS Tutorial

CSS Units

Understanding px, rem, vh, and the math of sizing

Absolute vs. Relative

In CSS, you can size elements using Absolute units (which are the same size everywhere) or Relative units (which scale based on something else).

1. Absolute Units

UnitDescription
pxPixels: The standard fixed unit. Good for borders or fixed icons.

2. Relative Units (The Pro Way)

Wait! Relative units are the secret to building "Responsive" websites that look good on both phones and 4K monitors.
UnitBased on...Description
remRoot Font Size1rem = the font size of the <html> element (usually 16px).
emParent Font Size1em = the font size of the immediate parent.
%Parent SizeScales based on the width/height of the parent container.
vw / vhViewport1vw = 1% of the screen width. 1vh = 1% of the screen height.

Why use rem?

Wait! You should use rem for almost all your font sizes and spacing. If a user increases their browser's default font size (for better readability), your entire site will scale up beautifully. If you use px, everything stays tiny and hard to read.

The calc() Function

You can even do math directly in your CSS!
css
width: calc(100% - 40px);

Summary

TermDescription
pxFixed pixel size
remRelative to root (The standard for text)
vw / vhRelative to the screen size (Viewport)
vmin / vmaxRelative to the smaller or larger screen dimension
chBased on the width of the "0" character in the current font
Best ForBuilding flexible and accessible layouts
Logic"Scale based on context"
SafetyUse max-width to prevent content from becoming too wide
Moderndvh (Dynamic Viewport Height) solves mobile browser bar issues
StandardUse rem for accessibility; px for thin borders
IdentityUnits are the foundation of "Fluid Design"