CSS background
property is used to add a color or an image to the background of an element. For example,
h1 {
background: orange;
}
Browser Output
Here, the background
property adds orange
color as a background to the h1
element.
CSS Background as Shorthand Property
There are various CSS background properties that can be specified into a single background
property as a shorthand. The syntax of the background
shorthand property is,
background: background-image background-position / background-size background-repeat background-attachment background-origin background-clip background-color;
Here,
- background-image: allows to add an image as a background of an element
- background-position: specifies the position of the background image within the element
- background-size: specifies the size of the background image
- background-repeat: controls the repeating behavior of a background image
- background-attachment: controls whether the background image scrolls or remains fixed with the page's content
- background-origin: specifies the starting position of the background area within the element
- background-clip: defines the background area for an element to clip
- background-color: sets the background color in an element
Note: The order of the values of the shorthand background
property is recommended as syntax. If any of the values are skipped, then it takes the default value of that property value.
Example: CSS background Shorthand Property
Let's see an example,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>CSS background</title>
</head>
<body>
<!-- Adding a background image -->
</body>
</html>
body {
/* background shorthand property */
background: url("avatar.png") top center no-repeat lightgray;
}
Browser Output
In the above example,
background: url("avatar.png") top center no-repeat lightgray;
Is equivalent to,
body {
background-image: url("avatar.png");
background-position: top center;
background-repeat: no-repeat;
background-color: lightgray;
}