/

HTML / CSS / JavaScript Tutorial

CSS Property: background

[this page | pdf | back links]

The CSS (CSS1 and CSS3) background property is a shorthand property combining (up to) 8 of the background properties.

 

Valid property values (other than inherit and initial) are defined by the elements of the shorthand. Shorthand elements (in the order in which they appear):

 

-        background-color

-        background-image

-        background-position

-        background-size

-        background-repeat

-        background-origin

-        background-clip

-        background-attachment

 

Default Value:

See individual properties

JavaScript syntax:

e.g. object.style.background="red url(mypicture.gif) top left no-repeat"

Inherited:

No

Animatable:

See individual properties

 

If one of the properties in the shorthand declaration is the background-size property then you need to use a “/” to separate it from the background-position property (the background-size property was added in CSS3), e.g.:

 

div {background: url(mypicture.gif) 10px 20px/40px 40px;}

 

More than one background-image can be specified. However, if you are using multiple background-image sources and also want a background-color then you need to put the background-color parameter last in the list.

 

EXAMPLE:


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

<script>
document.getElementById("x2").style.background =
  "red url(NematrianLogo.png) top left no-repeat";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyBackground() {
  var x = document.createElement("DIV"); x.style.background = "red url(NematrianLogo.png) top left no-repeat"; return (window.getComputedStyle(x, null).background == "red url(NematrianLogo.png) top left no-repeat");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile