CSS Background
The CSS background properties set a colour or an image behind the content of an element.
| Property | Meaning |
|---|---|
background-color | Background colour |
background-image | Background image, with url() or a gradient |
background-repeat | repeat, repeat-x, repeat-y or no-repeat |
background-position | Where the image starts, like center or top right |
background-size | auto, cover, contain or a size |
background-attachment | scroll or fixed (stays while scrolling) |
Background colour
body { background-color: #f5f5f5; }
.box { background-color: lightblue; }
Output in the browser
This box has a light blue background.
Background image
.hero {
background-image: url("images/banner.jpg");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
height: 300px;
}
covermakes the image fill the whole box, and some part may be cut.containshows the whole image, and the box may have empty space.- By default an image repeats in both directions, so use
no-repeatfor big pictures.
Shorthand
.hero {
background: #333 url("images/banner.jpg") no-repeat center / cover;
}
The order is: colour, image, repeat, position, then / size.
Multiple backgrounds
.box {
background-image: url("star.png"), linear-gradient(#fff, #ddd);
}
See also CSS Gradients.
Note:
Put text over a background image only when there is good contrast. Also set a background-color as a backup, in case the image does not load.
Summary
- Use
background-colorandbackground-imageto set the background. - Control the image with repeat, position and size.
- Use
backgroundas the shorthand. - Next: CSS Gradients.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |