Lesson 7 +10 XP

CSS Backgrounds

CSS Backgrounds

Backgrounds decorate the space behind your content, like wallpaper for elements!

background-color

A simple flat color behind the element.

div {
  background-color: lightblue;
}

You can use any color value: names, hex, rgb, hsl.

background-image

Put a picture behind an element.

body {
  background-image: url("bg.jpg");
}

background-repeat

By default images tile (repeat) to fill the space. Control it:

body {
  background-image: url("bg.jpg");
  background-repeat: no-repeat;   /* one copy */
  background-repeat: repeat-x;    /* only horizontal */
  background-repeat: repeat-y;    /* only vertical */
}

positioning: background-position and size

Place the image and tell it how big to be:

body {
  background-image: url("bg.jpg");
  background-repeat: no-repeat;
  background-size: cover;            /* fill the area, cropping */
  background-position: center;       /* center it */
}
  • background-size: cover fills the whole box without stretching (may crop).
  • background-size: 100% also stretches the image to the full.

attachment

background-attachment controls whether the background scrolls with the page:

body {
  background-image: url("bg.jpg");
  background-attachment: fixed;   /* background stays still while page scrolls */
}

Options: scroll (default), fixed, local.

The shorthand

Put them all in one line with the background shorthand:

body {
  background: lightblue url("bg.jpg") no-repeat center / cover;
}

Order matters: position and size are "position / size", and it's a lot to remember, that's why many devs write the individual properties.

Multiple backgrounds

You can stack several images, comma-separated:

div {
  background-image: url("top.png"), url("base.png");
  background-repeat: no-repeat;
}

TL;DR

  • background-color: flat color.
  • background-image: picture behind content.
  • background-repeat: controls tiling.
  • background-size: cover: fills box.
  • background-attachment: fixed: stays put while scrolling.
  • Short `background` shorthand exists.
  • Layer multiple images with commas.