前言
通过 CSS 背景属性,可以给页面元素添加背景样式,包括background-color
、background-image
、background-repeat
、background-position
等
1.background-color
<style>
div {
background-color: skyblue;
}
</style>
background-color
属性定义了元素的背景颜色- 一般情况下默认颜色是transparent(透明),我们也可以手动指定背景颜色为透明色
2.background-image
<style>
div {
background-image: none | url(URL)
}
</style>
background-image
属性描述了元素的背景图像- 背景图片后面的地址,千万不要忘记加URL,同时里面的路径不要加引号
3.background-repeat
<style>
div {
background-repeat: repeat| no-repeat| repeat-x| repeat-y
}
</style>
background-repeat
属性定义背景图像的平铺
参数值 | 作用 |
---|
repeat | 背景图像在纵向和横向上平铺(默认的) |
no-repeat | 背景图像不平铺 |
repeat-x | 背景图像在横向上平铺 |
repeat-y | 背景图像在纵向平铺 |
4.background-position
<style>
div {
background-position: x y;
}
</style>
background-position
属性可以改变图片在背景中的位置- 可以使用方位名词或者精确单位
参数值 | 说明 |
---|
length | 百分数 |
position | top丨center 丨 bottom 丨left 丨center 丨right 方位名词 |
5.background-attachment
<style>
div {
background-attachment : scroll | fixed
}
</style>
background-attachment
属性设置背景图像是否固定或者随着页面的其余部分滚动
参数 | 作用 |
---|
scroll | 背景图像是随对象内容滚动 |
fixed | 背景图像固定 |
6.背景复合写法
属性的值的书写顺序官方没有强制的标准。为了可读性,建议如下写:
<style>
div {
background: transparent url(URL) repeat-x fixed top;
}
</style>
background
: 背景颜色 背景图片地址 背景平铺 背景图像滚动 背景图片位置
7. 背景半透明
<style>
div {
background : rgba(0,0,255,0.5);
}
</style>
- 最后一个参数是alpha 透明度 ,取值范围在0~1之间
- 背景半透明是指盒子背景半透明,盒子里面的内容不受影响
8.背景总结
属性 | 作用 | 值 |
---|
background-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);后面必须是四个值 |