Colors and Units
The ways to express color in CSS, and the difference between absolute and relative length units.
2 min read
Almost every CSS property that takes a number needs a unit, and almost every property that takes a color has several equivalent ways to write it. Picking the right one affects both readability and how your design responds to change.
Expressing color
.a { color: red; } /* named color */
.b { color: #ff0000; } /* hex */
.c { color: rgb(255 0 0); } /* rgb */
.d { color: rgb(255 0 0 / 50%); } /* rgb with alpha (transparency) */
.e { color: hsl(0 100% 50%); } /* hue, saturation, lightness */All five describe the same or a related red. Hex is the most common in practice (easy to copy from design tools), but hsl() is often easier for humans to reason about: adjusting lightness to make a color darker or lighter is far more intuitive than guessing new hex digits. The / 50% syntax adds an alpha channel for transparency to any of these formats.
Absolute units: px
.box {
border: 1px solid black;
}px (pixels) is an absolute unit — 16px is 16px regardless of context. It's predictable, which makes it a reasonable choice for things that shouldn't scale with the user's font settings, like a hairline border.
Relative units: %, em, rem
.container {
width: 80%;
}
.card {
padding: 1.5em;
font-size: 1.2rem;
}%is relative to the parent element's size (usually width, for width-related properties).emis relative to the current element's font size — so1.5empadding on a.cardwithfont-size: 20pxcomputes to30px. This meansemvalues compound as they nest, which can surprise you.rem("root em") is relative to the root (<html>) element's font size, which stays constant no matter how deeply an element is nested — making it far more predictable thanemfor most sizing.
Why rem for font sizes matters for accessibility
html {
font-size: 100%; /* respects the user's browser font-size setting */
}
h1 {
font-size: 2rem;
}Using rem for font sizes (instead of px) means that if a user increases their browser's default font size for readability, your entire page scales proportionally instead of staying locked at a fixed pixel size. This is a small habit with a real accessibility payoff.
Viewport units
.hero {
height: 100vh;
font-size: clamp(1.5rem, 4vw, 3rem);
}vw and vh are relative to the viewport's width and height — 100vh means "the full height of the visible browser window." clamp(min, preferred, max) picks a value that scales with the viewport (4vw here) but never goes below 1.5rem or above 3rem, a common technique for responsive text without a media query.