CSSLesson 4 of 10Jump to practice
Colors and backgrounds
Set text and background colors with names, hex codes and rgb(), and add gradients.
Ways to write a color
All of these are the same teal color:
| Format | Example | Notes |
|---|---|---|
| Name | teal |
140+ names. Easy, but limited choice |
| Hex | #008080 |
Red, green, blue as two hex digits each, from 00 to ff |
| Short hex | #088 |
Works when each pair repeats: #008888 |
| rgb() | rgb(0 128 128) |
Each channel from 0 to 255. Older code writes rgb(0, 128, 128) |
| hsl() | hsl(180 100% 25%) |
Hue (0 to 360 on the color wheel), saturation, lightness |
Hex is the most common in real projects, because design tools give you hex codes.
<!DOCTYPE html>
<html>
<head>
<style>
p { padding: 8px; margin: 6px 0; color: white; font-family: sans-serif; }
.a { background-color: teal; }
.b { background-color: #d9480f; }
.c { background-color: rgb(80 60 200); }
.d { background-color: hsl(330 70% 45%); }
</style>
</head>
<body>
<p class="a">A color name: teal</p>
<p class="b">Hex: #d9480f</p>
<p class="c">rgb(80 60 200)</p>
<p class="d">hsl(330 70% 45%)</p>
</body>
</html>Text and background
colorsets the text color.background-colorsets the color behind the element.
See-through colors
Add a fourth value after a slash to set the opacity, from 0% (invisible) to 100% (solid).
<!DOCTYPE html>
<html>
<head>
<style>
.photo {
background: linear-gradient(90deg, orange, crimson);
padding: 30px;
}
.label {
background-color: rgb(0 0 0 / 50%);
color: white;
padding: 10px;
font-family: sans-serif;
}
</style>
</head>
<body>
<div class="photo">
<div class="label">Half-transparent black over color</div>
</div>
</body>
</html>Gradients
linear-gradient() fades between colors. It’s an image, so it goes in background or background-image, not background-color.
.hero {
background: linear-gradient(135deg, #0b7a75, #123b3c);
}
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Give the whole page a pale blue background.
body { : #eaf4ff; }Exercise 2Solved
Write pure red as a hex code.
h1 { color: ; }Red at full strength (
ff), green and blue at zero (00).Exercise 3Solved
Make the text white using
rgb()..banner { color: rgb(, , ); }White is every color channel at its maximum.
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.