CSS Basics: Using Multiple Backgrounds

Avatar of Chris Coyier
Chris Coyier on (Updated on )

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

With CSS, you can control the background of elements. You can set a background-color to fill it with a solid color, a background-image to fill it with (you guessed it) an image, or even both:

body {
  background-color: red;
  background-image: url(pattern.png);
}

Here’s an example where I’m using an SVG image file as the background, embedded right in the CSS as a data URL.

See the Pen background color and image together by Chris Coyier (@chriscoyier) on CodePen.

That’s just a single image there, repeated, but we can actually set multiple background images if we want. We do that by separating the values with commas.

body {
  background-image: 
    url(image-one.jpg),
    url(image-two.jpg);
}

If we leave it like that, image-one.jpg will repeat and entirely cover image-two.jpg. But we can control them individually as well, with other background properties.

body {
  background-image: 
    url(image-one.jpg),
    url(image-two.jpg);
  background-position:
    top right, /* this positions the first image */
    bottom left; /* this positions the second image */
  background-repeat:
    no-repeat; /* this applies to both images */
}

See how background-position also has comma-separated values? Those will apply individually to each image respectively. And then how background-repeat has only one value? We could have done two values in the same way, but by using just one value, it applies to both.

Here’s an example using four separate images, one in each corner, offset by a smidge:

See the Pen Example of multiple backgrounds by Chris Coyier (@chriscoyier) on CodePen.

It’s too bad you can’t rotate or flip background images or else we could have used just one. We can rotate and flip entire elements (or pseudo elements) though, so in cases like that, we can get away with using a single image!

See the Pen Flipping Image So You Can Use Just One by Chris Coyier (@chriscoyier) on CodePen.

Just a few other things to be aware of here:

  1. The stacking order of multiple background is “first is on top.”
  2. Gradients are applied through background-image, so they can be used as part of all this. For example, you could set a transparent gradient over a raster image.

See the Pen Tinted Image w/ Multiple Backgrounds by Chris Coyier (@chriscoyier) on CodePen.