CSS Background and Borders: Using CSS multiple backgrounds

CSS Background and Borders: Using CSS multiple backgrounds

With CSS3, you can apply multiple backgrounds to elements. These are layered atop one another with the first background you provide on top and the last background listed in the back. Only the last background can include a background color.

Specifying multiple backgrounds is easy:

.myclass {
  background: background1, background 2, ..., backgroundN;
}

You can do this with both the shorthand background property and the individual properties thereof except for background-color. That is, the following background properties can be specified as a list, one per background: background, background-attachment, background-clip,background-image, background-origin, background-position, background-repeat, background-size.

Example

In this example, three backgrounds are stacked: the Firefox logo, a linear gradient, and an image of bubbles:

HTML

<div class="multi_bg_example"></div>

CSS

.multi_bg_example {
  width: 100%;
  height: 400px;
  background-image: url(https://mdn.mozillademos.org/files/11305/firefox.png), url(https://mdn.mozillademos.org/files/11307/bubbles.png), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
  background-repeat: no-repeat, no-repeat, no-repeat;
  background-position: bottom right, left, right;
  background: -moz-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -webkit-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), -ms-linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0)), linear-gradient(to right, rgba(30, 75, 115, 1), rgba(255, 255, 255, 0));
}

Result

(If image does not appear in CodePen, click the TIdy button in the CSS section)

As you can see here, the Firefox logo (listed first) is on top, followed by the gradient, which is layered atop the bubbled background. Each subsequent sub-property (background-repeat and background-position) applies to the corresponding backgrounds. So the first listed value for background-repeat applies to the first (frontmost) background, and so forth.

See also

© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Background_and_Borders/Using_CSS_multiple_backgrounds

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部