CSS Color Formats: Hex, RGB and HSL

Hex Colors

A hex color writes red, green and blue channels as pairs of hexadecimal digits (00-ff) prefixed with a hash.

.box {
  background: #1e90ff; /* red=1e, green=90, blue=ff */
}

A shorthand form doubles each digit, so #0f0 is shorthand for #00ff00 (pure green).

RGB and RGBA

rgb() writes the same three channels as plain numbers from 0-255, which many people find easier to read and calculate than hex pairs. Adding a fourth alpha value controls transparency.

.box {
  background: rgb(30 144 255);
  border: 1px solid rgb(30 144 255 / 0.4); /* 40% opacity */
}

HSL and HSLA

hsl() describes color by hue (position on a color wheel, 0-360), saturation (how intense) and lightness (how close to black or white). This makes it intuitive to create a family of related colors just by changing one number.

.primary      { background: hsl(210 90% 55%); }
.primary-dark { background: hsl(210 90% 35%); } /* same hue, darker */

Which Format to Choose

FormatBest for
HexCopying exact values from a design tool, quick one-off colors
RGBWhen transparency is needed and channel values are already known
HSLBuilding color variations (lighter/darker/desaturated) from a single base hue
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.