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#FF0000for 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 asrgb(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
EasyYou 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:
- Write a CSS rule that targets the
<h1>element. Set thebackground-colortoyellow. - Write a CSS rule that targets the
<p>element. Set thebackground-colorto#00FF00(green). - Write a CSS rule that targets the
<div>element. Set thebackground-colortorgb(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>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Styling with CSS
5 Colors and Backgrounds
Background ColorHEX ColorsRGB ColorsTransparency with RGBARecap Challenge #1