CSS background-color

The background-color property in CSS is used to set the background color of an element. It supports predefined color names, hexadecimal, RGB, RGBA, HSL, HSLA values, and more. This property allows developers to add color to the background of elements, enhancing the visual appeal of a webpage.


Syntax of background-color

</>
Copy
background-color: color | transparent | initial | inherit;

Values

ValueDescription
colorSpecifies a color value (e.g., red, #ff0000, rgb(255,0,0)).
transparentMakes the background color fully transparent.
initialSets the property to its default value (transparent).
inheritInherits the background color value from the parent element.

Default Value

transparent


Examples for background-color

Using the CSS background-color Property

The following examples demonstrate how to use the background-color property with different values.

</>
Copy
/* Using a predefined color */
.element {
  background-color: red;
}

/* Using a hexadecimal color */
.element {
  background-color: #00ff00;
}

/* Using RGB color */
.element {
  background-color: rgb(0, 0, 255);
}

/* Transparent background */
.element {
  background-color: transparent;
}

Example for Applying Background Color with Hexadecimal Colors

Below is an example demonstrating the use of the background-color property with a hexadecimal value:

background-color: #ffcc00;

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  .box {
    width: 200px;
    height: 100px;
    background-color: #ffcc00;
    display: flex;
    justify-content: center;
    align-items: center;
    color: black;
    font-size: 18px;
    border: 2px solid black;
  }
</style>
</head>
<body>

<div class="box">Hex Color: #ffcc00</div>

</body>
</html>

Example for Applying Background Color with Predefined Colors

background-color: red;

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
<style>
  .box {
    width: 200px;
    height: 100px;
    background-color: red;
    display: flex;
    justify-content: center;
    align-items: center;
    color: black;
    font-size: 18px;
    border: 2px solid black;
  }
</style>
</head>
<body>

<div class="box">Color: red</div>

</body>
</html>

Browser Support

The background-color property is widely supported across all modern browsers. Below is a compatibility table:

BrowserVersion
Chrome1.0
Edge4.0
Firefox1.0
Safari1.0
Opera3.5