In this section, we will learn what the background property is and how to use it in CSS.
Click here to run the example of background property.
CSS background Property Definition and Usage
The background property is a shorthand property to declare values for other background related properties all in one declaration.
The properties that the background property supports are:
background-color
background-image
background-position
background-size
background-repeat
background-origin
background-clip
background-attachment
CSS background Property Syntax
background: bg-color bg-image position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit;
Note: between background-position and background-size it’s important to use a forward-slash ‘/’.
CSS background Property Value
As mentioned before, this property is a shorthand property to set the values for a set of background related properties. Hence the values we could use for those properties can be used in this property as well.
Note: we don’t need to specify a value for each background related property in the background. Any property we leave out will be set to its default value.
For example:
background: url(photos/music.jpg);
The example above is equivalent to:
background: url(photos/music.jpg) left top / 100% repeat scroll border-box border-box transparent;
Note: the two global values “initial” and “inherit” can also be used.
Example: background property in CSS
<!DOCTYPE html>
<html>
<head>
<title>CSS is fun :)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
*{
margin:unset;
box-sizing: border-box;
}
div{
width:50vw;
height:30vh;
border:1em dashed hsla(195, 83%, 50%,0.5);
border-radius: 0.3em;
padding: 1em;
margin:0.5em;
}
.one{
background:url(photos/music.jpg) center top / 20px 30px no-repeat border-box border-box red;
}
.two{
background:url(photos/music.jpg) center center / 30px 20px no-repeat content-box content-box green;
}
.three{
background:url(photos/music.jpg) center bottom / 2em 3em no-repeat border-box border-box blue;
}
h1{
color: red;
}
</style>
</head>
<body>
<div class = "one">
</div>
<div class = "two">
</div>
<div class = "three">
</div>
</body>
</html>