2. Modern CSS Layout & Design Systems
CSS Units, Variables & Smooth Transitions
Understand px vs rem vs % vs vh, define reusable theme tokens using CSS Custom Properties (--variables), and add polished hover transitions.
- Choose the right CSS unit (px, rem, %, dvh) for typography and layout
- Centralize theme colors with reusable CSS custom properties (--variables)
- Add smooth 60fps hover interactions with CSS transitions
Clean websites feel effortless because spacing, colors, and hover interactions stay consistent everywhere. Two CSS features make that easy: CSS Variables and Transitions.
Choosing the Right CSS Unit
| Unit | Meaning | Best Used For |
|---|---|---|
px | Fixed screen pixels | Thin 1px borders, subtle shadows |
rem | Relative to root <html> font size (usually 16px) | Font sizes, padding, margins (respects browser zoom!) |
% | Percentage of parent container | Fluid widths (width: 100%) |
vh / dvh | Percentage of viewport (screen) height | Full-height hero sections (min-height: 100dvh) |
CSS Custom Properties (Variables)
Define your brand colors once inside :root, then reuse them across your entire stylesheet with var(--name):
:root {
--brand: #4f46e5;
--brand-hover: #4338ca;
--surface: #ffffff;
--text: #0f172a;
}
.btn {
background: var(--brand);
color: white;
}
.btn:hover {
background: var(--brand-hover);
}If you ever rebrand from indigo to emerald, you change one line in :root! Even better, you can build dark mode or theme variants by overriding those exact variables on [data-theme="dark"]:
[data-theme="dark"] {
--surface: #0f172a;
--text: #f8fafc;
}Fluid Typography with clamp()
Instead of jumping abruptly across breakpoints, clamp(min, preferred, max) scales font sizes smoothly with viewport width while keeping a readable floor and ceiling:
h1 {
font-size: clamp(1.75rem, 3vw + 1rem, 3rem);
}Smooth Hover Effects with transition
Instead of a button snapping harshly on hover, transition smoothly animates property changes:
.card {
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.card:hover {
transform: translateY(-3px);
box-shadow: 0 10px 25px rgba(15, 23, 42, 0.08);
}Animating transform and opacity runs smoothly on the GPU, whereas animating width or margin forces the browser to recalculate layout every frame. Also respect users sensitive to motion with @media (prefers-reduced-motion: reduce) { * { transition: none !important; } }.
Try It Live: CSS Variables & Hover Transition
Change --accent to #059669 (emerald) or #e11d48 (rose), click Run & Preview, and hover over the button:
Quick Checkpoints
Why should font sizes and spacing generally use rem instead of fixed px?
Which two CSS properties can animate smoothly at 60fps on the GPU without forcing layout recalculation?