CSS ยท Chapter 7 of 44

CSS Backgrounds

The background properties let you set an element's background color, image, repeat behavior, position, and size.

The background shorthand property combines several of these into a single declaration for convenience.

Syntax
background: color image repeat position;

Background color and image

background-color sets a solid fill. background-image sets a picture, which can repeat by default unless controlled with background-repeat.

Position and size

background-position places the image, and background-size controls scaling, with keywords like cover and contain being common.

Example 1 (css)
body {
  background-image: url('bg.jpg');
  background-repeat: no-repeat;
  background-size: cover;
}
Output
A full-page, non-repeating background image scaled to cover the viewport

background-size: cover scales the image to fill the element while keeping aspect ratio.

Key points

  • background-color sets a solid fill color.
  • background-image adds a picture background.
  • background-repeat controls tiling.
  • background-size: cover/contain controls scaling.
๐Ÿ’ก Note: Combine properties using the background shorthand to write less code.

๐Ÿ“ Quick Quiz

1. Which property sets a background picture?

2. Which value makes a background scale to fill an element?

3. Which property stops a background image from tiling?