CSS 背景属性
| 属性 | 描述 |
|---|---|
| background | 简写属性,作用是将背景属性设置在一个声明中。 |
| background-attachment | 背景图像是否固定或者随着页面的其余部分滚动。 |
| background-color | 设置元素的背景颜色。 |
| background-image | 把图像设置为背景。 |
| background-position | 设置背景图像的起始位置。 |
| background-repeat | 设置背景图像是否及如何重复。 |
背景色【background-color】 属性用纯色来填充背景。
- background-color: blue;
- background-color: rgb(0, 0, 255);
- background-color: #0000ff;
背景图【background-image 】属性允许指定一个图片展示在背景中
background-image: url(images/image.jpg);
背景平铺【background-repeat】设置背景图片时,默认把图片在水平和垂直方向平铺以铺满整个元素。
- background-repeat: repeat; /* 默认值,在水平和垂直方向平铺 */
- background-repeat: no-repeat; /* 不平铺。图片只展示一次。 */
- background-repeat: repeat-x; /* 水平方向平铺(沿 x 轴) */
- background-repeat: repeat-y; /* 垂直方向平铺(沿 y 轴) */
- background-repeat: inherit; /* 继承父元素的 background-repeat 属性*/
背景定位【background-postion】属性用来控制背景图片在元素中的位置。
- /* 例 1: 默认值 */background-position: 0 0; /* 元素的左上角 */
- /* 例 2: 把图片向右移动 */background-position: 75px 0;
- /* 例 3: 把图片向左移动 */background-position: -75px 0;
- /* 例 4: 把图片向下移动 */background-position: 0 100px;
顺序方面和使用像素值时的顺序几乎一样,首先是 x 轴,其次是 y 轴,像这样:
background-position: top right;
浏览器是以元素的百分比数值来设置图片的位置的。看例子就好理解了。假设设定如下:
background-position: 100% 50%;背景附着【background-attachment】属性决定用户滚动页面时图片的状态。三个可用属性为 scroll(滚动),fixed(固定) 和 inherit(继承)。inherit 单纯地指定元素继承他的父元素的 background-attachment 属性。
如果设置 background-attachment: scroll,就设置了当元素滚动时,元素背景也必需随着滚动。
background-image: url(test-image.jpg);
background-position: 0 0;
background-repeat: no-repeat;
background-attachment: scroll;
效果:当向下滚动页面时,背景向上滚动直至消失。
当设置 background-attachment 为 fixed 时,当页面向下滚动时,背景要待在它原来的位置(相对于浏览器来说)。也就是不随元素滚动。
background-image: url(test-image.jpg);
background-position: 0 100%;
background-repeat: no-repeat;
background-attachment: fixed;
效果:页面已经向下滚动了,但是图像仍然保持可见。
背景的简写属性【background】
background-color: transparent;
background-image: url(image.jpg);
background-position: 50% 0 ;
background-attachment: scroll;
background-repeat: repeat-y;
以上语句可以简写成:background: transparent url(image.jpg) 50% 0 scroll repeat-y;