Colors, Units & Variables
CSS supports many color formats and measurement units. Choosing the right ones makes your layouts responsive, accessible, and easy to maintain.
1 Color Formats
CSS — Color Formats
/* Named colors (limited palette) */
color: red;
color: tomato;
/* Hex — #RRGGBB or shorthand #RGB */
color: #2563eb;
color: #fff; /* = #ffffff */
/* RGB / RGBA */
color: rgb(37, 99, 235);
color: rgba(37, 99, 235, 0.5); /* 50% transparent */
/* HSL — Hue Saturation Lightness (most designer-friendly) */
color: hsl(220, 83%, 53%);
color: hsla(220, 83%, 53%, 0.8);
/* Modern oklch (wide-gamut, best for design systems) */
color: oklch(55% 0.2 265);
2 Length Units
| Unit | Meaning | Use When |
|---|---|---|
px | Pixels (absolute) | Borders, shadows, icons |
rem | Root font-size multiple | Font sizes, spacing (responsive) |
em | Parent font-size multiple | Component-relative sizing |
% | Relative to parent | Widths, heights |
vw / vh | Viewport width / height | Full-screen sections |
ch | Width of "0" character | Readable line lengths |
3 CSS Custom Properties (Variables)
CSS — Custom Properties
:root {
--color-primary: #2563eb;
--color-surface: #1e293b;
--color-text: #f1f5f9;
--radius-md: 8px;
--spacing-lg: 24px;
}
.btn {
background: var(--color-primary);
border-radius: var(--radius-md);
padding: var(--spacing-lg);
color: var(--color-text);
}
5 Code Challenge
Challenge: Define a
:root block with at least 4 custom properties (primary color, background, text color, border radius). Use them throughout a mini card component.