Menu
Coddy logo textTech

Background Color

Part of the Styling with CSS section of Coddy's HTML journey — lesson 25 of 76.

In CSS, the background-color property is used to set the background color of an HTML element. This property allows you to specify a color value.

Here's the basic syntax for using the background-color property:

selector {
    background-color: color-value;
}

Here are a few common ways to specify color values in CSS:

  • Named colors: Predefined color names, such as red, blue, green, black, white, etc.
  • Hexadecimal values: Six-digit color codes preceded by a hash symbol (#), such as #FF0000 for red.
  • RGB values: Specifies the red, green, and blue components of a color using the rgb() function, with values ranging from 0 to 255, such as rgb(255, 0, 0) for red.

For example:

body {
    background-color: lightblue;
}

h1 {
    background-color: #FF0000;
}

p {
    background-color: rgb(0, 0, 255);
}

In this example, the background color of the <body> element is set to lightblue, all <h1> headings have a red background (#FF0000), all <p> (paragraph) elements have a blue background (rgb(0, 0, 255)).

challenge icon

Challenge

Easy

You are given an HTML document with a heading (<h1>), a paragraph (<p>), and a division (<div>). Your task is to use the background-color property to style these elements. Follow the steps below:

  1. Write a CSS rule that targets the <h1> element. Set the background-color to yellow.
  2. Write a CSS rule that targets the <p> element. Set the background-color to #00FF00 (green).
  3. Write a CSS rule that targets the <div> element. Set the background-color to rgb(255, 0, 255) (magenta).

Cheat sheet

The background-color property sets the background color of an HTML element:

selector {
    background-color: color-value;
}

Color values can be specified using:

  • Named colors: red, blue, green, black, white
  • Hexadecimal values: #FF0000 (red)
  • RGB values: rgb(255, 0, 0) (red)
body {
    background-color: lightblue;
}

h1 {
    background-color: #FF0000;
}

p {
    background-color: rgb(0, 0, 255);
}

Try it yourself

<html>
<head>
    <title>Background Color</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body>
    <h1>This is a heading</h1>
    <p>This is a paragraph.</p>
    <div>This is a division.</div>
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Styling with CSS