Backgrounds

Solid Colors, Images, and the `background` Shorthand

Backgrounds

An element can have a color background, an image background, or multiple stacked backgrounds. Many properties — but a shorthand pulls them together.

4 min read Level 1/5 #css#backgrounds#images
What you'll learn
  • Set a color or image background
  • Use `background-size`, `position`, `repeat`
  • Stack multiple backgrounds

background controls the painted area BEHIND the content. A solid color, an image, a gradient, or several stacked together.

Solid Color

.card { background-color: #f4f4f5; }
.card { background: #f4f4f5; }   /* shorthand — same thing */

Background Image

.hero {
  background-image: url("/hero.jpg");
  background-size: cover;             /* fill the box, cropping if needed */
  background-position: center;
  background-repeat: no-repeat;
}

The most common combo. cover fits the image without distortion, cropping to fill. contain fits without cropping (may leave gaps).

The background Shorthand

background:
  #111
  url("/hero.jpg") center / cover
  no-repeat;

Order: color image position / size repeat. The slash separates position and size.

Multiple Backgrounds

Stack several — they’re painted top-down (first is on top):

.section {
  background:
    linear-gradient(rgb(0 0 0 / 50%), rgb(0 0 0 / 50%)),   /* dark overlay */
    url("/photo.jpg") center / cover;
}

A photo with a translucent overlay for legibility.

background-attachment

.parallax {
  background-attachment: fixed;   /* image stays put while content scrolls */
}

Performance hit on mobile — use sparingly.

background-clip — Limit The Painted Area

.gradient-text {
  background: linear-gradient(45deg, tomato, gold);
  background-clip: text;
  color: transparent;
}

Paints the background only WITHIN the text. Modern, well-supported trick.

Up Next

Gradients in depth.

Gradients →