CSS Background Shorthand
The background shorthand sets several background properties in a single declaration, keeping your CSS compact.
One property, many values
Instead of writing separate lines for color, image, repeat, position, and more, the <background> shorthand lets you list them all at once. The browser assigns each value to the matching longhand property.
The shorthand
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #fff url('bg.jpg') no-repeat center / cover;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<p>Page content.</p>
</body>
</html>The same rule written out
The shorthand above is equivalent to the longhand rules below. Both produce identical results; the shorthand is simply shorter.
Longhand equivalent
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: #fff;
background-image: url('bg.jpg');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
</style>
</head>
<body>
<h1>Welcome</h1>
<p>Page content.</p>
</body>
</html>What you can include
- background-color
- background-image
- background-repeat
- background-position
- background-size (written after position with a slash)
- background-attachment
Note: The shorthand resets any background property you leave out to its default. If you set background: #fff and had a background-image earlier, that image is cleared. Set everything you need in the one declaration.
Note: When you only need to change one value, the individual longhand property such as background-color is clearer and avoids accidental resets.
Exercise: CSS Backgrounds
Which property sets an image as an element's background?