CSS Units
px, em, rem, %, vw, vh, clamp()
Skills taught: css.units, css.viewport-units, css.fluid-sizing
Absolute units
/* px — screen pixels. Fixed. Never scales with font preferences */
.border { border: 1px solid #2d3748; } /* good use: fine lines */
.icon { width: 24px; height: 24px; } /* good use: icons */
/* AVOID px for font-size — it ignores user browser preferences */
.bad { font-size: 16px; } /* does not scale with user settings */
.good { font-size: 1rem; } /* scales correctly */
Relative units — em and rem
/* rem — relative to <html> font-size (default 16px) */
:root { font-size: 16px; } /* browser default — usually don't set this */
h1 { font-size: 2.5rem; } /* 40px */
h2 { font-size: 1.75rem; } /* 28px */
p { font-size: 1rem; } /* 16px */
/* em — relative to the CURRENT element's font-size */
/* Use em for padding/spacing that should scale with font-size */
.button {
font-size: 1rem;
padding: 0.5em 1em; /* 8px 16px — scales if font-size changes */
}
Percentage and viewport units
/* % — percentage of the parent element's dimension */
.sidebar { width: 25%; } /* quarter of parent's width */
/* vw / vh — 1% of viewport width / height */
.hero {
width: 100vw; /* full viewport width */
min-height: 100vh; /* full viewport height */
}
/* svh — small viewport height (mobile-safe, excludes browser chrome) */
.hero { min-height: 100svh; }
/* ch — width of '0' character — ideal for line length */
article { max-width: 65ch; }
clamp() — fluid sizing without media queries
/* clamp(minimum, preferred, maximum) */
/* preferred grows with viewport — min and max cap the extremes */
h1 {
/* Minimum 1.5rem, grows with viewport, caps at 3rem */
font-size: clamp(1.5rem, 4vw, 3rem);
}
.container {
/* Between 16px and 64px of padding, scales with viewport */
padding: clamp(1rem, 5vw, 4rem);
max-width: clamp(320px, 90%, 1200px);
}
Tip: Quick guide: Use rem for font sizes. Use em for padding/margin that should scale with the element's own font. Use % or fr for widths. Use clamp() for fluid sizes that need no media query.
Frequently Asked Questions
Why should I avoid px for font sizes?
Users can change their browser's base font size in settings (for accessibility). Fonts set in px ignore this preference. rem-based fonts respect it, making your site accessible to users who need larger text.
What is the difference between vw and %?
% is relative to the parent element's width. vw is relative to the viewport (browser window) width. A child set to 100% fills its parent. A child set to 100vw fills the entire screen width regardless of parent.