CodeMIRAI
0 XP

Colours

2 min read 5 runnable examples Quiz included

CSS gives you several ways to write the same colour.

Named colours

HTML
<p style="color: tomato">tomato</p>
<p style="color: teal">teal</p>
<p style="color: rebeccapurple">rebeccapurple</p>

There are about 140 names. They're handy for quick tests, but designs use exact values.

Hex codes

#RRGGBB: two hexadecimal digits each for red, green and blue, from 00 (none) to ff (full):

HTML
<style>
  .swatch { display: inline-block; width: 90px; padding: 22px 0; margin: 4px; text-align: center; color: white; border-radius: 8px; font-family: monospace; }
</style>
<span class="swatch" style="background:#ff0000">#ff0000</span>
<span class="swatch" style="background:#5a48f5">#5a48f5</span>
<span class="swatch" style="background:#0aa9cf">#0aa9cf</span>
<span class="swatch" style="background:#222">#222</span>

#222 is shorthand for #222222.

rgb() and rgba()

The same three channels as numbers from 0 to 255, plus an optional alpha for transparency (0 is invisible, 1 is solid):

HTML
<div style="background: rgb(90, 72, 245); color: white; padding: 10px">rgb(90, 72, 245)</div>
<div style="background: rgb(90 72 245 / 0.4); padding: 10px">40% opacity</div>

hsl(): hue, saturation, lightness

hsl() is often the easiest to reason about: pick a hue (0–360 on the colour wheel), a saturation (grey to vivid) and a lightness (black to white):

HTML
<style>
  .h { display: inline-block; width: 70px; height: 50px; margin: 2px; border-radius: 6px; }
</style>
<span class="h" style="background: hsl(250 90% 30%)"></span>
<span class="h" style="background: hsl(250 90% 50%)"></span>
<span class="h" style="background: hsl(250 90% 70%)"></span>
<span class="h" style="background: hsl(250 90% 90%)"></span>
<br>
<span class="h" style="background: hsl(0 80% 60%)"></span>
<span class="h" style="background: hsl(120 60% 45%)"></span>
<span class="h" style="background: hsl(200 80% 50%)"></span>
<span class="h" style="background: hsl(45 95% 55%)"></span>

Change only the lightness and you get a whole family of shades of one colour.

Text and background

HTML
<style>
  .banner { color: #ffffff; background-color: #1f2937; padding: 16px; border-radius: 10px; font-family: system-ui; }
  .banner strong { color: #fbbf24; }
</style>
<div class="banner">Readable text needs <strong>enough contrast</strong> with its background.</div>
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.