--- title: background-image slug: Web/CSS/background-image tags: - CSS Background - CSS Property - CSS_参考 - Reference translation_of: Web/CSS/background-image ---
CSS background-image 属性用于为一个元素设置一个或者多个背景图像。
此交互实例的代码被存储于Github仓库. 如果你想对这些交互实例贡献代码, 请clone https://github.com/mdn/interactive-examples 并向我们发起拉取请求.
在绘制时,图像以 z 方向堆叠的方式进行。先指定的图像会在之后指定的图像上面绘制。因此指定的第一个图像“最接近用户”。
然后元素的边框 border 会在它们之上被绘制,而 {{cssxref("background-color")}} 会在它们之下绘制。图像的绘制与盒子以及盒子的边框的关系,需要在CSS属性{{cssxref("background-clip")}} 和 {{cssxref("background-origin")}} 中定义。
如果一个指定的图像无法被绘制 (比如,被指定的 URI 所表示的文件无法被加载),浏览器会将此情况等同于其值被设为 none。
每个背景图像被明确规定为关键字 none 或是一个 {{cssxref("<image>")}} 值。
可以提供由逗号分隔的多个值来指定多个背景图像:
background-image:
linear-gradient(to bottom, rgba(255,255,0,0.5), rgba(0,0,255,0.5)),
url('https://mdn.mozillademos.org/files/7693/catfront.png');
none<image>注意星星图片部分透明且位于猫图片上方.
<div>
<p class="catsandstars">
This paragraph is full of cats<br />and stars.
</p>
<p>This paragraph is not.</p>
<p class="catsandstars">
Here are more cats for you.<br />Look at them!
</p>
<p>And no more.</p>
</div>
p {
font-size: 1.5em;
color: #FE7F88;
background-image: none;
background-color: transparent;
}
div {
background-image:
url("https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png");
}
.catsandstars {
background-image:
url("https://mdn.mozillademos.org/files/11991/startransparent.gif"),
url("https://mdn.mozillademos.org/files/7693/catfront.png");
background-color: transparent;
}
{{EmbedLiveSample('Examples')}}
浏览器不会向辅助技术提供有关背景图像的任何特殊信息。这对于屏幕阅读器来说非常重要,因为屏幕阅读器不会告知用户它的存在,因而不能向用户传达任何信息。如果图像包含对理解页面总体目的至关重要的信息,则最好在文档中作出语义性地描述(describe it semantically)。
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('CSS3 Backgrounds', '#background-image', 'background-image')}} | {{Spec2('CSS3 Backgrounds')}} | From CSS2 Revision 1, the property has been extended to support multiple backgrounds and any {{cssxref("<image>")}} CSS data type. |
| {{SpecName('CSS2.2', 'colors.html#propdef-background-image', 'background-image')}} | {{Spec2('CSS2.2')}} | From CSS1, the way images with and without intrinsic dimensions are handled is now described. |
| {{SpecName('CSS1', '#background-image', 'background-image')}} | {{Spec2('CSS1')}} | Initial definition. |
{{cssinfo}}
[1] 如果 about:config 中 browser.display.use_document_colors 被设置为 false, 背景图像将不会展示.
[2] 当前的iOS Safari 版本 (5.0) CSS 背景属性对SVG的支持并不完善. iOS Safari (5.0)之前的版本亦是如此.