CSS Background Color


In CSS The background-color property is used to specify the background color of an element. Background includes the total size of the element with padding and border but not the margin. The use is to make text attractive and easy to read for the user.


Syntax:


element {
  background-color: color|transparent|initial|inherit;
}



Let’s see what function does each property has.


Color


This defines the background color value by color names or HEX avlues or RGB values. Let's check an example.


h1 {
/* All h1 tags will have blue background */
  background-color: blue;
}



Let check it in a web page:


<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color:#ace1af;
}
h1 {
  color: white;
  background-color: #22b4b7;
}
h2 {
  color: rgb(255, 255, 255);
  background-color: #e35259;
}
</style>
</head>
<body>

<h1>Getting started with background-color </h1>
<h2> Trying different colors in hex and rgb</h2>

</body>
</html>

Live Demo!


Output:

Getting started with background-color

Trying different colors in hex and rgb


Transparent


It tells the browser that the background color should be transparent and is the default value too.

Syntax:


element {
  background-color:transparent;
}



For example:


<!DOCTYPE html>
<html>
<head>
<style>
body {
  text-align:center;
  background-color: #F7DC6F;
}
h1 {
  background-color: transparent;
}
</style>
</head>
<body>

<h1>Trying background color property </h1>
<h2> Trying transparent</h2>

</body>
</html>

Live Demo!


Output:

Trying background color property

Trying transparent


Initial


This is not used for assigning a color but to set the default value of the property in CSS. The keyword "initial" can be used on any HTML element or CSS property.


Syntax:


element {
    background-color: initial;
}



Inherit

This keyword specifies that an element should inherit value from its parent element.


Syntax:


h1 {
  background-color: inherit;
}