Skip to content
Retr0 Academy
CSS

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.

Open in Playground

Units

Absolute units

  • px: pixels. Precise and predictable; great for borders and small details.

Relative units

UnitRelative to
%The parent element's size
emThe current element's font size
remThe root (html) font size, usually 16px
vw / vh1% of the viewport's width / height
chThe 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(), or hsl(); add / alpha for transparency.
  • Backgrounds can be colors, images, or gradients.
  • Use rem for type and spacing, % and vw/vh for fluid sizes, px for fine details.
  • Check color contrast so everyone can read your text.
Open in Playground

Saved in this browser.