CSS Colors: Names, Hex, rgb() and hsl() Explained
Color is the first thing most people change in CSS. The color property sets text color, background-color fills an element's background, and border-color paints borders. All of them accept the same color formats.
Four ways to write a color
- Keywords:
navy,teal,tomato, plustransparentandcurrentColor, which means "whatever the text color is". There are about 150 named colors; they are handy for quick tests. - Hex codes:
#0e7490is three pairs of hexadecimal digits for red, green and blue, each from00toff. A short form like#0afdoubles each digit (#00aaff). rgb():rgb(14 116 144)gives the same three channels as decimal numbers from 0 to 255. The older comma formrgb(14, 116, 144)still works everywhere.hsl():hsl(192 82% 31%)describes hue (an angle on the color wheel, 0 = red, 120 = green, 240 = blue), saturation and lightness. It is the easiest to tweak by hand: keep the hue, lower the lightness, and you get a darker shade of the same color.
Transparency
Add a fourth value, the alpha channel, after a slash: rgb(14 116 144 / 50%) is half transparent. Hex has an eight-digit form for the same thing (#0e749080). This is different from the opacity property, which fades the whole element including its text and children. To tint just a background, use an alpha color on background-color.
Try it
Four swatches use four syntaxes. Two of them describe the same teal, and the script asks the browser for the computed value of each. Browsers report colors in a normalized rgb() form, which is a reliable way to compare them.
Expected page text
hex: rgb(14, 116, 144) rgb: rgb(14, 116, 144) hsl: rgb(255, 0, 0) alpha: rgba(14, 116, 144, 0.5)
The first two lines print the same value because #0e7490 and rgb(14 116 144) are the same color. The alpha color is reported with an rgba() form that keeps the transparency.
Readable color pairs
Pretty colors are useless if people cannot read the text. The Web Content Accessibility Guidelines ask for a contrast ratio of at least 4.5:1 between normal body text and its background. Dark slate text on white passes easily; light gray on white usually fails. Browser developer tools show the contrast ratio when you inspect a text color, so check it before you ship.
Common mistakes
- Writing a hex code without
#:color: 0e7490is invalid and is ignored. - Using
opacityto fade a background and accidentally fading the text too. - Relying on color alone to signal meaning, such as red for errors. Add an icon or text too.
Summary
- Keywords, hex,
rgb()andhsl()all describe colors; pick whichever is clearest. - Add
/ alphafor transparency;opacityfades the whole element. - Check text contrast, aiming for at least 4.5:1.
Quiz: Colors