通过CSS背景属性,可以给页面元素添加背景样式
1、背景颜色
background-color
属性定义了元素的背景颜色
background-color: 颜色值;
一般情况下元素背景默认是transparent(透明)
,也可以手动指定背景颜色为透明色。
2、背景图片
background-image
属性描述了元素的背景图像,实际开发常见于logo或者一些装饰性的小图片或者是超大的背景图片,优点是非常便于控制位置(精灵图也是一种运用场景)
background-image: none | url(url)
3、背景平铺
如果需要在HTML页面上对背景图像进行平铺,可以使用background-repeat
属性。
background-repeat: repeat | no-repeat | repeat-x | repeat-y
属性值 | 作用 |
---|---|
repeat | 在x和y方向上都平铺 |
no-repeat | 不平铺 |
repeat-x | 在x方向上平铺 |
repeat-y | 在y方向上平铺 |
注意:
- 页面元素既可以添加背景颜色也可以添加背景图片,只不过背景图片会压住背景颜色
4、背景图片位置
利用background-position属性可以改变图片在背景中的位置
background-position: x y;
参数值代表的意思是:x坐标和y坐标,可以使用方位名词或者精确单位
参数值 | 说明 |
---|---|
length | 百分数 、 由浮点数字和单位标识符组成的长度值 |
position | top 、 center 、 bottom 、 left 、 right 方位名词 |
参数是方位名词:
- 如果是方位名词,
center right
和right center
是一样的,不区分顺序,因为right/lift一定是水平的,top/bottom一定是垂直的; - 如果只指定了一个方位名词,另一个值省略,则第二个值默认居中对齐;
参数是精确单位:
- 如果参数值是精确坐标,那么第一个肯定是x坐标,第二个一定是y坐标
- 如果只指定一个数值,那该数值一定是x坐标,另一个默认垂直居中
参数是混合单位:
- 如果指定的两个值是精确单位和方位名词混合使用,则第一个值是x坐标,第二个值是y坐标
5、背景图像固定
background-attachment
属性设置背景图像是否固定或者随着页面的其余部分滚动
background-attachment: scroll | fixed
6、背景属性复合写法
当使用简写属性时,没有特定的书写顺序,一般习惯约定顺序为:
background: background-color background-image background-repeat background-attachment background-position
eg:
background: transparent url(image.jpg) repeat-y fixed top center
7、背景颜色半透明
css3为我们提供了背景颜色半透明的效果
background: rgba(0,0,0,0.3)
- 最后一个参数是alpha透明度,取值范围在0~1之间
- 我们习惯把0.3的0省略掉,写为
background: rgba(0, 0, 0, .3);
8、背景总结
属性 | 作用 | 值 |
---|---|---|
bacjground-color | 背景颜色 | 预定于的颜色值/十六进制/RGB代码 |
background-image | 背景图片 | url(图片路径) |
background-repeat | 是否平铺 | repeat/no-repeat/repeat-x/repeat-y |
background-position | 背景位置 | length/position,分别是x和y坐标 |
background-attachment | 背景附着 | scroll(背景滚动)/ fixed(背景固定) |
背景简写 | 书写更简单 | 背景颜色 背景图片 背景平铺 背景固定 背景位置 |
背景色半透明 | 背景颜色半透明 | background: rgba(0,0,0,0.3);后面必须是4个值 |