CSS Basics: Using Multiple Backgrounds

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 adata 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 setmultiple 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 andflip entire elements (orpsuedo 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. Thestacking 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
.

CSS-Tricks稿源:CSS-Tricks (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » CSS Basics: Using Multiple Backgrounds

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录