CSS Backgrounds
CSS backgrounds let you add color, images, gradients, and patterns behind any element. Six longhand properties combine into one shorthand.
Background properties
| Property | Purpose | Example |
|---|---|---|
background-color | Solid colour behind the element. | #04AA6D |
background-image | A URL, gradient, or multiple layered images. | url('hero.jpg') |
background-repeat | Whether/how the image tiles. | no-repeat |
background-position | Where the image starts. | center top |
background-size | How the image is scaled. | cover, contain |
background-attachment | Whether the image scrolls with the page. | fixed |
cover vs contain
The shorthand
background shorthand
background: #04AA6D url('hero.jpg') no-repeat center/cover fixed;
/* color image repeat pos/size scroll */
Tip: You can stack multiple images by separating them with commas — earlier images sit on top. Use this for gradient overlays on photographs.
Example
Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>
<h1>CSS Backgrounds</h1>
<div class="box">Edit the CSS on the left, then click Run »</div>
</body>
</html>
Try it Yourself »
Exercise
Set the background image without tiling it.
body {
background-image: url('bg.png');
background-repeat:
;
}
Two words joined with a hyphen.
Discussion
Loading…