Units and CSS Variables
Sizes in CSS need a unit. Picking the right one makes your page look good on every screen.
Fixed pixel sizes made sense when everyone used similar screens. Today the same page is seen on a 5-inch phone and a 27-inch monitor, and some people set bigger text in their browser. Relative units like %, rem and vw let your design scale naturally instead of breaking.
px- fixed pixels. Good for borders and small details.%- a part of the parent's size.width: 50%is half of the parent.rem- relative to the page's base font size (usually 16px).2rem= 32px. Best for font sizes and spacing.em- relative to the element's own font size.vw/vh- 1% of the screen's width / height.100vhis a full screen tall.
<!DOCTYPE html>
<html>
<head>
<style>
.hero { height: 40vh; background: #ede9fe; padding: 1rem; }
h1 { font-size: 2rem; }
.half { width: 50%; background: #fde68a; }
.note { font-size: 0.875rem; }
</style>
</head>
<body>
<div class="hero">
<h1>2rem heading</h1>
<div class="half">I am 50% wide</div>
<p class="note">A smaller note in rem.</p>
</div>
</body>
</html>▶ Try it yourselfCSS variables (custom properties)
Write a value once and use it everywhere. Variables start with two dashes and are read with var(). Change the variable and every place using it changes.
Variables turn your design into a small set of decisions: your brand colour, your corner radius, your spacing size. Large sites define these once (often called design tokens) so the whole site stays consistent, and a re-design or dark mode means changing a few values instead of hundreds of rules.
<!DOCTYPE html>
<html>
<head>
<style>
:root {
--brand: #7c3aed;
--radius: 12px;
--space: 1rem;
}
.card {
border: 2px solid var(--brand);
border-radius: var(--radius);
padding: var(--space);
margin-bottom: var(--space);
}
.btn {
background: var(--brand);
color: white;
border: none;
border-radius: var(--radius);
padding: 0.5rem 1rem;
}
</style>
</head>
<body>
<div class="card">A card in the brand colour.</div>
<button class="btn">Buy now</button>
</body>
</html>▶ Try it yourselfTry changing --brand to #e11d48 and run it again.
calc()
calc() does maths with mixed units, for example width: calc(100% - 40px);.
@media (prefers-color-scheme: dark) { ... }.- px fixed; % of parent; rem of the base font; vw/vh of the screen.
- CSS variables: define with --name, use with var(--name).
- calc() mixes units in maths.
