CSS基础教程: 背景属性
Hudson 译 原文
CSS 中的 background 属性用于设置元素的背景。可以使用一个或多个图像设置背景 ,以及定义背景颜色、大小、位置、重复行为和其他相关属性。
background 属性具有丰富特性,用于样式化元素的外观并为网页添加视觉效果。
background 是以下属性的缩写:
background-attachment:指定背景相对于视口的位置,可以是固定或可滚动的。background-clip:控制背景图像超出元素填充或内容框的程度。background-color:设置元素的背景颜色。background-image:设置一个或多个元素的背景图像。background-origin:设置背景的起点。background-position:设置背景中每个图像的初始位置。background-repeat:控制背景中图像的重复方式。background-size:控制背景图像的大小。
概述
background属性允许设置一个或多个背景层,用逗号分隔。背景中的每一层可以有零个或至少一个以下值的出现:
<attachment><bg-image><position><bg-size><repeat-style>
如果要添加<bg-size>,则必须立即包含在<position>之后,用/分隔。例如:left/50%。
<box>的值可以包含零、一次或两次。根据出现次数,设置以下值:
-
once-设置背景源background-origin和背景剪裁background-clip的值。 -
twice-第一个值设置背景源background-origin的值,第二个值设置背景剪辑background-clip的值。
背景颜色background-color的值可以包含在指定为背景的最后一层中。
可能的值
以下是background可以具有的可能值:
<attachment>:指定背景的位置,固定或可滚动。默认为滚动。<box>:默认为border-box和padding-box。<background-color>:设置背景的颜色。默认为透明。<bg-image>:设置一个或多个背景图像。默认为无。<position>:设置背景的初始位置。默认为0% 0%。<repeat-style>:控制背景中图像的重复。默认为重复。<bg-size>:控制背景图像的大小。默认为自动。
语法
background = background-color | bg-image | bg-position / bg-size | repeat-style | attachment | box;
示例
CSS 背景 - 带图像和背景颜色
以下是使用简写属性 background 设置背景的示例,其中指定了图像和背景颜色:
<html>
<head>
<style>
body {
background: url('images/scenery2.jpg') center/40% 50% no-repeat fixed padding-box content-box lightblue;
}
</style>
</head>
<body>
<h2>简写背景</h2>
</body>
</html>
CSS 背景 - 图像重复
以下是使用简写属性 background 设置背景的示例,其中图像被重复:
<html>
<head>
<style>
body {
background: url('images/scenery2.jpg') repeat fixed padding-box content-box lightblue;
}
</style>
</head>
<body>
<h2 style="color: white;">简写背景 - 背景重复</h2>
</body>
</html>
CSS 背景 - 图像与背景颜色
以下是使用简写属性 background 设置背景的示例,其中添加了两个图像和一个背景颜色:
<html>
<head>
<style>
body {
background: url('images/orange-flower.jpg') right bottom/30% 60% no-repeat,
url('images/pink-flower.jpg') left top/30% 60% no-repeat lightgoldenrodyellow;
}
</style>
</head>
<body>
<h2 style="color: black; text-align: center;">简写背景 - 两个图像</h2>
</body>
</html>
其它相关属性
以下是与背景相关的所有属性:
| 属性 | 描述 |
|---|---|
background | 背景相关属性的缩写。 |
background-attachment | 指定背景相对于视口的位置,可以是固定或可滚动的。 |
background-clip | 控制背景图像超出元素填充或内容框的程度。 |
background-color | 设置元素的背景颜色。 |
background-image | 设置一个或多个元素的背景图像。 |
background-origin | 设置背景的起点。 |
background-position | 设置背景中每个图像的初始位置。 |
background-position-x | 设置背景中每个图像的初始水平位置。 |
background-position-y | 设置背景中每个图像的初始垂直位置。 |
background-repeat | 控制背景中图像的重复方式。 |
background-size | 控制背景图像的大小。 |
background-blend-mode | 确定元素的背景图像如何混合在一起。 |