• Angular
  • React
  • NextJs
  • Sass

How to Set Background color in CSS

By Webrecto, August 20, 2023

The CSS provides background-color property for adding background color in html elements. When we use the background-color property in CSS, It changes the element's background color and covers the total size, including padding and border. But the background-color property can not cover the margin area.

Background-color property can apply in any HTML element by class or inline CSS. It allows the solid and opacity to both color as the element's background and It is specified as a single color value.

Syntax:

background-color: color-name | transparent | initial | inherit;

The color-name is the value of background-color properties. We can set any type of color in place of color-name.

The transparent value of this property is the default value, which set the transparent background color of an element.

The background-color property set different type of color value.

  • Valid color name : "green"
  • Hex color value : "#ccff00"
  • Rgb color value : "rgb(258,0,0)"

Complete Example:

In this example, We will use different color value in css for set element background color.

<html>
 <head>
    <title>How to Set Background color in CSS</title>
    <style>
        body {
            text-align: center;
            background-color: navy; //Valid color name
        }
        h1 {
            color: #ffffff;
            background-color: #a0a0ba; //Hex color value
        }
        h2 {
            color: rgb(255 255 255);
            background-color: rgb(196 120 120); //Rgb color value
        }
    </style>
</head>
 <body>
    <h1>WebRecto.com</h1>
    <h2>background-color: color-name;</h2>
 </body>
</html>

Output:

How to Set Background color in CSS

In this example, We will use transparent value in background-color. Element will not display any color.

<html>
 <head>
    <title>How to Set Background color in CSS</title>
    <style>
        body {
            text-align: center;
            background-color: transparent;
        }
 
        h1 {
            background-color: transparent;
        }
 
        h2 {
            background-color: transparent;
        }
    </style>
</head>
 <body>
    <h1>WebRecto.com</h1>
    <h2>background-color: color-name;</h2>
 </body>
</html>

Output:

How to Set Background color in CSS