The background property is used for setting or getting the background image associated with an element. It is a shorthand property and can manipulate upto 8 properties.
Syntax
Following is the syntax for −
Setting the background property −
object.style.background = "color image repeat attachment position size origin clip|initial|inherit"
Values
Following are the values −
| Sr.No | Value & Description |
|---|---|
| 1 | color For setting an element background color. |
| 2 | image For setting an element background image. |
| 3 | repeat For setting how the background image will be repeated. |
| 4 | attachment For setting the background image at fixed or scrolls with the page. |
| 5 | position For setting the background image starting position. |
| 6 | size For setting the background image size. |
| 7 | origin For specifying the background positioning area. |
| 8 | clip For setting how far the background image is painted. |
Example
Let us look at an example for the background property −
<!DOCTYPE html>
<html>
<head>
<style>
#PIC{
width: 250px;
height: 150px;
border:solid 3px black;
font-weight:100;
text-align:center;
color:white;
font-size:40px;
background: url("https://www.tutorialspoint.com/python/images/python-mini.jpg") no-repeat fixed 2% 8%;
}
</style>
<script>
function changeBackground(){
document.getElementById("PIC").style.backgroundImage="url(https://www.tutorialspoint.com/csharp/images/csharp-mini-logo.jpg)";
document.getElementById("Sample").innerHTML="The background URL is now changed and new background image can be seen.";
}
</script>
</head>
<body>
<h2>Learning is fun</h2>
<div id="PIC">Tutorial</div>
<p>Click the below button to change the above background image for the div</p>
<button onclick="changeBackground()">CHANGE BACKGROUND</button>
<p id="Sample"></p>
</body>
</html>Output
This will produce the following output −

On clicking the CHANGE BACKGROUND image −
