CSS 基础:使用多个背景

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 价值 200 美元的免费积分!

使用 CSS,您可以控制元素的背景。您可以设置一个 background-color 以填充它为纯色,一个 background-image 以填充它为(你猜对了)图像,或者甚至两者兼而有之。

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

以下是一个示例,其中我使用 SVG 图像文件作为背景,直接嵌入到 CSS 中作为 数据 URL

查看 CodePen 上 Chris Coyier (@chriscoyier) 的笔 背景颜色和图像组合

这只是一个单一的图像,重复,但我们实际上可以设置 多个背景 图像,如果我们想要。我们通过用逗号分隔值来实现这一点。

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

如果我们保持这种状态,image-one.jpg 将重复并完全覆盖 image-two.jpg。但是我们也可以用其他背景属性分别控制它们。

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 */
}

请查看 background-position 有逗号分隔的值吗?这些将分别应用于每个图像。然后,background-repeat 如何只有一个值?我们也可以用同样的方法使用两个值,但通过只使用一个值,它适用于两者。

以下是一个使用四个独立图像的示例,每个图像都在一个角落,稍微偏移。

查看 CodePen 上 Chris Coyier (@chriscoyier) 的笔 多个背景的示例

太可惜了,你不能旋转或翻转背景图像,否则我们只需要使用一个。我们可以旋转和 翻转 整个元素(或 伪元素),因此,在这种情况下,我们可以使用一个图像!

查看 CodePen 上 Chris Coyier (@chriscoyier) 的笔 翻转图像,因此您可以只使用一个

这里还有其他一些需要注意的事项。

  1. 多个背景的 堆叠顺序 是“第一个在顶部”。
  2. 渐变通过 background-image 应用,因此它们可以用作所有这些内容的一部分。例如,您可以设置一个透明渐变覆盖光栅图像。

查看 CodePen 上 Chris Coyier (@chriscoyier) 的笔 带有多个背景的色调图像