Labs ICT
Pro Login

Backgrounds

Backgrounds are how you add visual depth to your pages. CSS gives you a ton of control over background colors, images, and how they behave.

background-color

The simplest background property. Sets the background color of an element.

div {
  background-color: #f0f8ff;
}

p {
  background-color: yellow;
}

background-image

Sets an image as the background. Use url() to point to the image file.

.hero {
  background-image: url("images/background.jpg");
}

By default, the image repeats to fill the element. You can control that with other properties.

background-repeat

Controls whether and how the background image repeats.

.box {
  background-image: url("pattern.png");
  background-repeat: no-repeat;
}

.tile {
  background-repeat: repeat-x;
}
  • repeat — default, repeats in both directions
  • no-repeat — shows the image once
  • repeat-x — repeats horizontally only
  • repeat-y — repeats vertically only

background-size

Controls how big the background image is.

.cover {
  background-size: cover;
}

.contain {
  background-size: contain;
}

.custom {
  background-size: 200px 100px;
}

cover makes the image fill the entire element (it may crop). contain makes the whole image visible (there may be empty space).

The Shorthand Property

You can combine all background properties into one background shorthand.

.hero {
  background: #2c3e50 url("bg.jpg") no-repeat center / cover;
}

Order: color, image, repeat, position, / size. It looks messy at first, but it saves a lot of lines once you get used to it.

Try it Yourself →