CSS backgrounds

The use of CSS background properties is for adding background effects for an elements.

 

CSS background-color 

You can specify the background color of an element using the background-color property.

Example: 

The background color of a page is set like this:

<!DOCTYPE html>
<html>
<head>
           <title>CSS background-color</title>
<style>
body {
  background-color: lightblue;
}
</style>
</head>
<body>
           <h1>Hello CSS</h1>
           
</body>
</html>

Try With Example

 

With CSS background properties, a color is most often specified by:

  • a valid color name - like "green" 
  • a HEX value - like "#ff0000" 
  • an RGB value - like "rgb(255,0,0)"

You can also look at CSS Color Values for an entire list of possible color values.

 

Other Elements 

The background color for any HTML element can be set.

Example:

In this example, the <h1>, <p>, and <div> elements will have different background colors:

<!DOCTYPE html>
<html>
<head>
           <title>CSS background-color</title>
<style>
h1 {
  background-color: green;
}

div {
  background-color: lightblue;
}

p {
  background-color: yellow;
}
  </style>
</head>
<body>
           <div style="height:100px; padding:10px">
             <h1>Welcome to CSS Tutorial</h1>
             <p>I am a CSS Developer!</p>
          </div>
           
</body>
</html>

Try With Example

 

Opacity / Transparency

The element's opacity/transparency is specified by the opacity property. It can take a value between 0.0 - and 1.0. The lower value means more transparency:

Example :

<!DOCTYPE html>
<html>
<head>
           <title>CSS background-color</title>
<style>
div {
  background-color: green;
  opacity: 0.3;
}
  </style>
</head>
<body>
           <div style="height:100px; padding:10px">
             <h1>Welcome to CSS Tutorial</h1>
             <p>I am a CSS Developer!</p>
          </div>
           
</body>
</html>

Try With Example

 

Transparency using RGBA

You can use RGBA color values if you do not wish to apply opacity to child elements, like in our example mentioned above. The example below sets the opacity for the background color only and not the text:

In the CSS colors tutorial, you learned that you could use RGB as a color value and that you can use an RGB color value with an alpha channel (RGBA) - that specifies the opacity for a color.

You can specify an RGBA color value(red, green, blue, alpha). Here, the alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

 

Tip: Learn more about RGBA Colors in our CSS Colors tutorial.

Example :

div {
  background: rgba(0, 128, 0, 0.3) /* Green background with 30% opacity */
}

Try With Example

 

The CSS Background Color Property

Property Description
background-color Sets the element's background color