该性质是用于定义一个元素的背景效果。
Background-color
该性质用来指定一个元素的背景颜色。
注意: The background of an element is the total size of the element, including padding and border (but not the margin).
一个元素的背景指的是除了外边距之外元素完整的大小,包含内边距和边框。
Background-image
该性质用于给一个元素指定一张图片作为背景。
body
{
background-image: url("img_tree.gif");
}
不要背景图:background-image: none;
Tip: Always set a background-color to be used if the image is unavailable.
以防背景图片不可用,记住要设置背景颜色。
Background-repeat
By default, a background-image is placed at the top-left corner of an element, andrepeated both vertically and horizontally,
默认情况下,背景图片被放置在一个元素的左上角,同时沿水平方向和垂直方向重复摆放。
有时为了更好的效果,只需要 repeat-x 水平重复或者 repeat-y 垂直重复。
如:实现从上到下颜色的渐变效果
body
{
background-image:url("gradient2.png");
background-repeat:repeat-x;
}
不需要重复时,设置性质的值为 no-repeat.
Background-position
使用该性质来定位背景图片的位置。
body
{
background-image:url("img_tree.png");
background-repeat:no-repeat;
background-position:right top;
}
可取的值:
left top left center left bottom right top right center right bottom center top center center center bottom | If you only specify one keyword, the other value will be "center" 如果只写一个关键词,另一个值将为“居中” |
x% y% | The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50% . Default value is: 0% 0% |
xpos ypos | The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions |
Background-attachment
该性质指定了一张背景图片是否位置固定,还是与页面剩余部分一起滚动。
取值:
- scroll:scrolls along with the element. This is default, 背景图像随页面其余部分一起滚动
- fixed:fixed with regard to the viewport,
- local:scrolls along with the element's contents, 和元素内容一起滚动。
Background-size
background-size: auto|length|cover|contain|initial|inherit;
1. cover
the background image will scale to cover the entire content area. Notice that the "cover" value keeps the aspect ratio, and some part of the background image may be clipped
背景图将放大以完全覆盖住内容区域。注意:背景图的 width 达到其所在元素宽度的100%,保持宽高比,等比放大,图片部分位置可能因此 invisible。
2. 100% 100%
图片的宽和高会拉伸以完全覆盖住内容区域,非等比放大。
3. contain
the background image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship between the image's width and height)
背景图会放大,尽力去填满内容区域(通常填不满),但是保持宽高比,等比放大,宽和高分别顶住所在元素的边缘。
Background-clip & Background-origin
- background-clip: border-box|padding-box|content-box|initial|inherit;
- background-origin: padding-box|border-box|content-box|initial|inherit;
简写Background性质
从上面的几个例子可以看到,许多性质都是在处理背景。为了简化代码,可以把一些性质写进一个单独的性质里。
The shorthand property for background is simply "background"
简写顺序需遵循如下规则:
- background-color
- background-image
- background-repeat
- background-attachment
- background-position
以上性质如果有一个或几个缺省,没关系,只有遵循这个顺序写就行。