CSS Colors
CSS lets you colour text, backgrounds and borders in several different ways.
Where Colours Are Used
| Property | What it colours |
|---|---|
color | The text |
background-color | The area behind the content |
border-color | The border line |
Colour Names
CSS knows about 140 colour names, such as red, navy, tomato, gold and seagreen. Names are easy to read but you only get a fixed set of colours.
Example
<!DOCTYPE html>
<html>
<head>
<style>
h2 { color: seagreen; }
p { background-color: gold; }
</style>
</head>
<body>
<h2>Green heading</h2>
<p>Text on a gold background</p>
</body>
</html>Try it Yourself »HEX Colours
A HEX colour starts with # and has six digits: two for red, two for green and two for blue. Each pair goes from 00 (none) to ff (full).
| HEX | Colour |
|---|---|
#ff0000 | Red |
#00ff00 | Bright green |
#0000ff | Blue |
#000000 | Black |
#ffffff | White |
#264de4 | The blue used in this tutorial |
There is also a short form with three digits: #f00 is the same as #ff0000.
RGB and RGBA
rgb() takes three numbers from 0 to 255 for red, green and blue. rgba() adds a fourth number, the alpha (transparency), from 0 (invisible) to 1 (solid).
Example
<!DOCTYPE html>
<html>
<head>
<style>
.box {
padding: 15px;
margin: 8px 0;
color: white;
}
.solid { background-color: rgb(38, 77, 228); }
.half { background-color: rgba(38, 77, 228, 0.5); }
.light { background-color: rgba(38, 77, 228, 0.2); color: black; }
</style>
</head>
<body>
<div class="box solid">rgb(38, 77, 228)</div>
<div class="box half">rgba with 0.5 alpha</div>
<div class="box light">rgba with 0.2 alpha</div>
</body>
</html>Try it Yourself »Modern browsers also accept a fourth value inside rgb() itself, like rgb(38 77 228 / 50%), but rgba() is still very common.
HSL Colours
HSL stands for hue, saturation, lightness. Many designers find it easier, because you can make a colour lighter or darker by changing one number.
- Hue: a position on the colour wheel, from 0 to 360 (0 is red, 120 is green, 240 is blue)
- Saturation: 0% is grey, 100% is the full colour
- Lightness: 0% is black, 50% is normal, 100% is white
Example
<!DOCTYPE html>
<html>
<head>
<style>
div { padding: 12px; color: white; }
.dark { background-color: hsl(200, 80%, 30%); }
.normal { background-color: hsl(200, 80%, 45%); }
.light { background-color: hsl(200, 80%, 70%); color: black; }
</style>
</head>
<body>
<div class="dark">Dark blue (lightness 30%)</div>
<div class="normal">Normal blue (lightness 45%)</div>
<div class="light">Light blue (lightness 70%)</div>
</body>
</html>Try it Yourself »Always check that text and background have enough contrast. Light grey text on a white background is hard to read, especially on a phone in the sun.
Exercise
Exercise
What colour is #000000?
