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.

Colors four ways
Open in editor
<!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>
Result

Text and background

  • color sets the text color.
  • background-color sets 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).

Transparency
Open in editor
<!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>
Result

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.

  1. Exercise 1

    Give the whole page a pale blue background.

    body {
      : #eaf4ff;
    }

  2. Exercise 2

    Write pure red as a hex code.

    h1 {
      color: ;
    }

  3. Exercise 3

    Make the text white using rgb().

    .banner {
      color: rgb(, , );
    }

Quiz: 3 questions

1. In the hex color #ff8800, which pair controls green?
2. What is rgb(0 0 0 / 50%)?
3. Why check the contrast between text and background colors?

Finish the practice to complete this lesson.