CSS background-color Property

CSS background-color property sets the background color for HTML Element(s).

The syntax to specify a value for background-color property is

background-color: value;

The following table gives the possible values that could be given to background-color property.

ValueDescriptionExample
colorAny valid CSS color value.background-color: red;
background-color: #f00;
background-color: rgb(25, 220, 85);
transparentSets background color to transparent.background-color: transparent;
initialSets background color to default value.background-color: initial;
inheritInherits background color value from its parent element.background-color: inherit;

Examples

In the following examples, we apply background-color using different types of allowed values for background-color property.

background-color with CSS Color Values

In the following example, we take multiple div elements, and set each of the element with different kind of allowed CSS Color Value. Refer CSS Color Values tutorial.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        div {
            height: 100px;
            width: 100px;
            display: inline-block;
            margin: 10px;
        }
        #div1 {
            background-color: #00cf66;
        }
        #div2 {
            background-color: rgb(222, 119, 160);
        }
        #div3 {
            background-color: rgba(222, 119, 160, 0.5);
        }
        #div4 {
            background-color: hsl(56, 100%, 64%);
        }
        #div5 {
            background-color: hsla(56, 100%, 64%, 0.5);
        }
        #div6 {
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
    <div id="div4"></div>
    <div id="div5"></div>
    <div id="div6"></div>
</body>
</html>

background-color for different HTML elements

In the following example, we take some different HTML elements like h1, p, a, span, and pre, and set background-color for these HTML elements.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <style>
        h1 {
            background-color: #3399ff;
        }
        p {
            background-color: #8ad084;
        }
        a {
            background-color: #7f94a9;
        }
        span {
            background-color: #ff33e7;
        }
        pre {
            background-color: #fffcb4;
        }
    </style>
</head>
<body>
    <h1>Heading 1</h1>
    <p>A paragraph.</p>
    <a href="#">Anchor Text</a>
    <p>A paragraph with a <span>span text</span>.</p>
    <pre>        pre
        hello
        world
    </pre>
</body>
</html>

Conclusion

In this CSS Tutorial, we learned about background-color property, and how to use this property for HTML Elements, with examples.