CSS Background

The CSS background properties set a colour or an image behind the content of an element.

PropertyMeaning
background-colorBackground colour
background-imageBackground image, with url() or a gradient
background-repeatrepeat, repeat-x, repeat-y or no-repeat
background-positionWhere the image starts, like center or top right
background-sizeauto, cover, contain or a size
background-attachmentscroll 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;
}
  • cover makes the image fill the whole box, and some part may be cut.
  • contain shows the whole image, and the box may have empty space.
  • By default an image repeats in both directions, so use no-repeat for 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-color and background-image to set the background.
  • Control the image with repeat, position and size.
  • Use background as 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.