/

HTML / CSS / JavaScript Tutorial

CSS Property: background-image

[this page | pdf | back links]

The CSS (CSS1) background-image property sets one or more background images for an element. The background of an element includes its padding and border but not its margin. Usually, you should set a background-color to be used if the image is unavailable and the background image and text colour should be chosen in tandem to make the text easy to read.

 

By default, a background image is placed at the top-left corner of an element and is repeated both vertically and horizontally. These features can be overridden using the background-position and background-repeat properties.

 

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

 

Value

Description

url(imagefile)

The URL of the image. To specify more than one image, separate the URLs with a comma

none

(default value). No background image supplied

 

Default Value:

none

JavaScript syntax:

e.g. object.style.backgroundImage="url(mypicture.gif)"

Inherited:

No

Animatable:

No

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
p {width: 200px}
p.x1 {background-image: url(NematrianLogo.png);}
</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.backgroundImage =
  "url(NematrianLogo.png)";
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedCSSPropertyBackgroundImage() {
  var x = document.createElement("DIV"); x.style.backgroundImage = "url(NematrianLogo.png)"; return (window.getComputedStyle(x, null).backgroundImage == "url(NematrianLogo.png)");
}


NAVIGATION LINKS
Contents | Prev | Next | CSS Properties


Desktop view | Switch to Mobile