CSS Background Shorthand
The background
shorthand property lets you combine multiple background properties into one line. This can simplify your code and make it more readable. You can set the image, color, position, size, repeat, and attachment all at once.
Key Topics
Shorthand Syntax
The order of values in the shorthand is not strict, but a common pattern is: background: [color] [image] [repeat] [attachment] [position] / [size];
. Not all values are required; omit what you don’t need.
Example of Using Shorthand
Combine multiple properties into a single background
declaration.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Background Shorthand Example</title>
<style>
body {
background: #f0f0f0 url('pattern.png') no-repeat fixed center / cover;
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
color: #333;
padding: 50px;
background-color: rgba(255,255,255,0.7);
}
</style>
</head>
<body>
<h1>Combined Background Properties</h1>
<p>Here, the background color, image, repeat setting, attachment, position, and size are all defined using a single shorthand property.</p>
</body>
</html>
Explanation: The shorthand property simplifies your CSS. One declaration sets the background color, the image, prevents repetition, fixes the background in place, centers the image, and sizes it to cover the screen.
Key Takeaways
- Convenience: Shorthand reduces CSS clutter.
- Flexibility: Include only the background values you need.
- Readability: One line can express a complex background setup.