/

HTML / CSS / JavaScript Tutorial

CSS Property: background-color

[this page | pdf | back links]

The CSS (CSS1) background-color property sets the background colour of an element. The background of an element includes its padding and border but not its margin. Usually, a background colour and text colour should be chosen in tandem to make the text easy to read.

 

Valid property values (other than inherit and initial) are:

 

Value

Description

color

Specified CSS colour

transparent

(default value). Transparent

 

Default Value:

transparent

JavaScript syntax:

e.g. object.style.backgroundColor="red"

Inherited:

No

Animatable:

Yes

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
p {width: 200px}
p.x1 {background-color: yellow;}
</style>
</head>
<body>
1. Element with default property<br>
<p>1</p><br>
2. Element set using in-file HTML style
<p class="x1">2</p><br>
3. Element set using JavaScript
<p id="x2">3</p>

<script>
document.getElementById("x2").style.backgroundColor =
  "yellow";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyBackgroundColor() {
  var x = document.createElement("DIV"); x.style.backgroundColor = "yellow"; return (window.getComputedStyle(x, null).backgroundColor == "yellow");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile