background-image 属性指定元素的背景图像。
可以使用一个或者多个图像。
默认情况下,背景图像垂直和水平重复并放置在元素的左上角。
元素的背景是它的总大小,包括填充(padding)和边框(不是边距(margin))。
如果图像不可用,则需要指定背景颜色。
| 初始值 | none |
|---|---|
| 应用于 | 所有元素。它也适用于:::first-letter 和 ::first-line。 |
| 继承 | 无效 |
| 可动画的 | 无效 |
| 版本 | CSS1+CSS3中的一些新值 |
| DOM 语法 | object.style.backgroundImage=“url(imgtree.png)”; |
语法
background-image: url | none | linear-gradient | radial-gradient | repeat-linear-gradient | repeat-radial-gradient | initial | inherit;
background-image 属性的示例:
<!DOCTYPE html>
<html>
<head>
<title>The title of the document</title>
<style>
body {
background-image: url("/uploads/media/default/0001/02/55a2f152f59bf42a99b576d44a4578ec9daa0ab6.png");
background-color: #8ebf42;
}
</style>
</head>
<body>
<h2>Background-image 属性示例</h2>
<p>Hello World!</p>
</body>
</html>
结果
请参阅另一个示例,其中使用了两个图像,它们是在 background-position 属性的帮助下指定的。
具有其他背景属性的 background-image 属性示例:
<!DOCTYPE html>
<html>
<head>
<title>The title of the document</title>
<style>
body {
padding: 100px;
background-image: url("/uploads/media/default/0001/02/55a2f152f59bf42a99b576d44a4578ec9daa0ab6.png"), url("/uploads/media/default/0001/01/b408569013c0bb32b2afb0f0d45e93e982347951.jpeg");
background-attachment: fixed;
background-position: 5px 50px;
background-repeat: no-repeat, repeat;
}
</style>
</head>
<body>
<h2>Background-image 属性示例</h2>
<p>The background image is positioned 5px from the left, and 50px down from the top.</p>
</body>
</html>
在这个例子中,带有两种颜色的“线性渐变”被指定为 <div> 元素的背景图像:
具有“线性渐变”值的背景图像属性示例:
<!DOCTYPE html>
<html>
<head>
<style>
div {
height: 300px;
background-image: linear-gradient(#eee, #1c87c9);
}
</style>
</head>
<body>
<h2>Linear gradient as a background image example</h2>
<p>This linear gradient starts at the top. It starts gray, transitioning to blue:</p>
<div></div>
</body>
</html>
具有“repeating-radial-gradient”值的背景图像属性示例:
<!DOCTYPE html>
<html>
<head>
<title>The title of the document</title>
<style>
div {
height: 300px;
background-color: #cccccc;
background-image: repeating-radial-gradient(#8ebf42, #eee 15%, #ccc 30%);
}
</style>
</head>
<body>
<h2>Radial gradient as a background image example</h2>
<div></div>
</body>
</html>
属性值说明
| 值 | 说明 |
|---|---|
| url | 定义图像的url。它可以指定为多个用逗号分隔的图像。 |
| none | 不会有任何背景图像。它是默认值。 |
| linear-gradient | 将线性渐变指定为背景图像。 |
| radial-gradient | 径向渐变指定为背景图像。 |
| repeat-linear-gradient | 重复线性渐变。 |
| repeat-radial-gradient | 重复径向渐变。 |
| initial | 将属性设置为其默认值。 |
| inherit | 从父元素继承属性。 |
日期:2020-06-02 22:14:16 来源:oir作者:oir
