CSS Tutorial
CSS Colors
Color is one of the first things you will style with CSS. You can specify colors by name, by HEX code, or with the RGB and HSL formats, giving you millions of options.
How CSS colors work
Almost every CSS color property, such as color for text or background-color for backgrounds, accepts a color value. CSS supports several ways to write that value, from simple names to precise numeric codes.
Named colors
CSS understands around 140 named colors, such as red, blue, tomato, teal and gold. Names are easy to read and great for learning, though they are limited compared with numeric formats.
h1 {
color: tomato;
}
p {
color: slategray;
}HEX colors
A HEX color is a hash followed by six hexadecimal digits: two for red, two for green, two for blue. For example, #ff0000 is pure red and #0000ff is pure blue. HEX is the most common format on the web.
body {
background-color: #f0f4ff;
}
h1 {
color: #2b5cff;
}RGB and RGBA
The rgb() format uses three numbers from 0 to 255 for red, green and blue. The rgba() format adds a fourth value, alpha, from 0 (fully transparent) to 1 (fully opaque), letting you create see-through colors.
h1 {
color: rgb(43, 92, 255);
}
.overlay {
background-color: rgba(0, 0, 0, 0.5); /* 50% transparent black */
}HSL colors
The hsl() format describes color by hue (0 to 360 degrees on a color wheel), saturation (a percentage) and lightness (a percentage). Many designers find HSL the most intuitive for adjusting shades.
h1 {
color: hsl(222, 100%, 58%);
}See the color formats live
<!DOCTYPE html>
<html>
<head>
<style>
div {
color: white;
padding: 14px;
margin: 6px 0;
font-family: Arial, sans-serif;
}
.named { background-color: tomato; }
.hex { background-color: #2b5cff; }
.rgb { background-color: rgb(34, 139, 34); }
.hsl { background-color: hsl(280, 60%, 45%); }
</style>
</head>
<body>
<div class="named">Named color: tomato</div>
<div class="hex">HEX: #2b5cff</div>
<div class="rgb">RGB: rgb(34, 139, 34)</div>
<div class="hsl">HSL: hsl(280, 60%, 45%)</div>
</body>
</html>Color formats reference
| Format | Example | Notes |
|---|---|---|
| Name | red | About 140 built-in names |
| HEX | #ff0000 | Most common on the web |
| RGB | rgb(255, 0, 0) | 0-255 for red, green, blue |
| RGBA | rgba(255, 0, 0, 0.5) | Adds transparency (alpha) |
| HSL | hsl(0, 100%, 50%) | Hue, saturation, lightness |
Use RGBA or HSLA when you need transparency, for example a semi-transparent overlay on top of an image.
Key points
- color sets text color; background-color sets background color.
- Colors can be names, HEX, RGB, RGBA or HSL.
- HEX (#rrggbb) is the most common web format.
- RGBA and HSLA add transparency via the alpha value.
- HSL is often the easiest format for tweaking shades.
