Course contentsShow
← Web Development
Lesson 482 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

Color Functions: rgb(), hsl(), and hwb()

Construct colors using functional notation with modern syntax including alpha transparency and optional commas.

Color Functions: rgb(), hsl(), and hwb()

You'll learn how to construct colors using modern CSS color functions with cleaner syntax and alpha transparency.

The Core Idea

CSS color functions let you define colors programmatically instead of using hex codes. The modern syntax is cleaner: no commas required, values separated by spaces, and an optional slash before alpha (transparency).

Three Color Functions

rgb() — Define colors using Red, Green, Blue channels (0-255 or 0%-100%):

.element {
  /* Modern syntax: space-separated, optional alpha with / */
  background-color: rgb(255 0 128);
  border-color: rgb(100% 0% 50% / 0.5); /* 50% transparent */
}

hsl() — Define colors using Hue (0-360 degrees), Saturation (0%-100%), Lightness (0%-100%):

.element {
  /* Hue: 210° (blue), Sat: 100%, Light: 50% */
  background-color: hsl(210 100% 50%);
  border-color: hsl(210 100% 50% / 0.8); /* With transparency */
}

hwb() — Define colors using Hue, Whiteness, Blackness (newer, more intuitive for some):

.element {
  /* Hue: 120° (green), 20% white mixed in, 10% black */
  background-color: hwb(120 20% 10%);
  color: hwb(0 0% 0% / 0.7); /* Black with transparency */
}

Alpha Transparency

All three support alpha by adding / value at the end (0-1 or 0%-100%):

.overlay {
  background-color: rgb(0 0 0 / 0.5); /* 50% transparent black */
}

Why Use These?

Unlike hex codes, color functions are human-readable and easier to adjust dynamically with calc() or custom properties.

Key Takeaway: Modern CSS color functions use space-separated values with optional / alpha notation, making colors more readable and flexible than hex codes—choose rgb() for direct control, hsl() for saturation/lightness tweaking, or hwb() for whiteness/blackness mixing.