CSS · 2 min read
Colors, Backgrounds, and Units
Use named, hex, RGB, and HSL colors, style backgrounds and gradients, and choose the right CSS unit.
Ways to write a color
css
.a { color: tomato; } /* named color */
.b { color: #ff6347; } /* hex: red, green, blue */
.c { color: rgb(255 99 71); } /* RGB, 0 to 255 */
.d { color: rgb(255 99 71 / 50%); } /* RGB with 50% opacity */
.e { color: hsl(9 100% 64%); } /* hue, saturation, lightness */- Hex colors are compact and common in design tools.
- HSL is very human-friendly: change the hue (0 to 360 degrees on the color wheel) to get a different color, or the lightness to get a lighter or darker shade.
Backgrounds
css
.hero {
background-color: #0f172a;
background-image: url("stars.jpg");
background-size: cover; /* fill the box, cropping if needed */
background-position: center;
background-repeat: no-repeat;
}Gradients
Gradients are images generated by CSS:
css
.sunset { background: linear-gradient(135deg, #ff7e5f, #feb47b); }
.glow { background: radial-gradient(circle, #fff, #a5b4fc); }<div class="swatch named">tomato</div>
<div class="swatch hex">#1572B6</div>
<div class="swatch hsl">hsl(280 70% 55%)</div>
<div class="swatch gradient">linear-gradient</div>
<div class="swatch glass">50% transparent</div>Edit this example in the Playground.
Units
Absolute units
px: pixels. Precise and predictable; great for borders and small details.
Relative units
| Unit | Relative to |
|---|---|
% | The parent element's size |
em | The current element's font size |
rem | The root (html) font size, usually 16px |
vw / vh | 1% of the viewport's width / height |
ch | The width of the "0" character in the current font |
css
html { font-size: 16px; }
h1 { font-size: 2.5rem; } /* 40px */
.container { width: 90%; max-width: 70ch; }
.hero { min-height: 100vh; } /* full screen height */Color contrast
Text must stand out from its background. The WCAG guideline asks for a contrast ratio of at least 4.5:1 for normal text. Light gray text on white might look stylish but can be unreadable for many people.
Summary
- Write colors as names, hex,
rgb(), orhsl(); add/ alphafor transparency. - Backgrounds can be colors, images, or gradients.
- Use
remfor type and spacing,%andvw/vhfor fluid sizes,pxfor fine details. - Check color contrast so everyone can read your text.
Saved in this browser.