Units, custom properties and responsive images
Pick px, rem, em, percent and vw correctly, reuse values with CSS variables, and serve images that fit each screen.
Three topics turn up in nearly every front-end screening and in the first week of any site job: which unit to use, how to avoid repeating the same colour fifty times, and how to stop images from breaking a phone layout.
Choosing a unit
- px is fixed. Good for borders and tiny details, poor for text that users may scale.
- rem is relative to the root font size, 16px in most browsers unless changed.
2remis 32px by default. - em is relative to the element's own font size, so it compounds. A button with
font-size: 20pxandpadding: 1emgets 20px of padding. - % is relative to the parent for widths, and to the parent's font size for text.
- vw and vh are 1 percent of the viewport width and height.
A common exam question: with html { font-size: 20px; }, what is 1.5rem? The answer is 30px. For fluid headings, clamp() keeps text between limits: font-size: clamp(1.25rem, 3vw, 2.5rem); never goes below 20px or above 40px at the default root size.
Custom properties
A custom property is a value you define once and reuse. Define it on :root for site-wide use, and override it lower in the tree or inside a media query.
:root {
--brand: #0a66c2;
--space: 1rem;
}
.btn {
background: var(--brand);
padding: var(--space);
}
@media(min-width: 768px) {
:root { --space: 1.5rem; }
}var(--missing, 8px) uses 8px when the property is not set. Names are case-sensitive, so --Brand and --brand are different.
Images that fit the screen
Start with the two lines that stop most overflow bugs: img { max-width: 100%; height: auto; }. Then give every image width and height attributes so the browser reserves space before the file arrives, which prevents the page from jumping. For large photos, offer several sizes with srcset and tell the browser how wide the image will display with sizes.
<img src="hero-800.jpg"
srcset="hero-400.jpg 400w, hero-800.jpg 800w, hero-1600.jpg 1600w"
sizes="(max-width: 600px) 100vw, 800px"
width="800" height="500"
loading="lazy"
alt="Two people reviewing a printed report at a desk">On a 375px-wide phone the browser picks the 400w file; on a desktop it picks 800w or 1600w depending on pixel density. Use <picture> only when you need a different crop on mobile, not just a smaller file.
Common mistakes and a practice habit
- Setting
width: 100vwon a block, which adds a horizontal scrollbar because the vertical scrollbar takes space. Use100%. - Adding
loading="lazy"to the first image above the fold, which delays the most important picture. - Writing srcset without sizes, so the browser assumes the image is full width and downloads too much.
Practice habit: rebuild one small component a day using only rem, custom properties and a responsive image, then resize the window from 320px to 1400px and watch for anything that overflows.
More in Web and app