1. 背景颜色(color)

  • 语法:

    1. background-color:颜色值;

    默认的值是 transparent (透明)

    2.背景图片(image)

  • 语法:

    1. background-image : none | url (url)
参数 作用
none 无背景图(默认的)
url 使用绝对或相对地址指定背景图像
  1. background-image : url(images/demo.png);
  • 小技巧: 我们提倡背景图片后面的地址,url不要加引号。

使用 background-size属性调整背景图像的大小:

  • cover —浏览器将使图像足够大,使它完全覆盖了盒子区,同时仍然保持其高宽比。在这种情况下,有些图像可能会跳出盒子外
  • contain — 浏览器将使图像的大小适合盒子内。在这种情况下,如果图像的长宽比与盒子的长宽比不同,则可能在图像的任何一边或顶部和底部出现间隙。

3. 背景平铺(repeat)

  • 语法:
    1. background-repeat : repeat | no-repeat | repeat-x | repeat-y
参数 作用
repeat 背景图像在纵向和横向上平铺(默认的)
no-repeat 背景图像不平铺
repeat-x 背景图像在横向上平铺
repeat-y 背景图像在纵向平铺

4. 背景位置(position) 重点

  1. background-position : length || length
  2. background-position : position || position 横|竖
参数
length 百分数
由浮点数字和单位标识符组成的长度值
position top
center
bottom
left
center
right 方位名词

注意

  • 1必须先指定background-image属性

1、参数是方位名词

  • 如果指定的两个值都是方位名词,则两个值前后顺序无关,比如 left top 和 top left 效果一致
  • 如果只指定了一个方位名词,另一个值省略,则第二个值默认居中对齐

2、参数是精确单位

  • 如果参数值是精确坐标,那么第一个肯定是 x 坐标,第二个一定是 y 坐标
  • 如果只指定一个数值,那该数值一定是 x 坐标,另一个默认垂直居中

3、参数是混合单位
如果指定的两个值是精确单位和方位名词混合使用,则第一个值是 x 坐标,第二个值是 y 坐标

实际工作用的最多的,就是背景图片居中对齐了。

  • 雪碧图
  • background-size

5. 背景附着

  • 背景附着就是解释背景是滚动的还是固定的
    1. background-attachment : scroll | fixed
    | 参数 | 作用 | | —- | —- | | scroll | 背景图像是随对象内容滚动 | | fixed | 背景图像固定 |

6. 背景简写

  • background:属性的值的书写顺序官方并没有强制标准的。为了可读性,建议大家如下写:
  • background: 背景颜色 背景图片地址 背景平铺 背景滚动 背景位置;
    1. background: transparent url(image.jpg) repeat-y scroll center top ;

7. 背景透明(CSS3)

  1. background: rgba(0, 0, 0, 0.3);
  • 最后一个参数是alpha 透明度 取值范围 0~1之间
  • 我们习惯把0.3 的 0 省略掉 这样写 background: rgba(0, 0, 0, .3);
  • 注意: 背景半透明是指盒子背景半透明, 盒子里面的内容不受影响
  • 因为是CSS3 ,所以 低于 ie9 的版本是不支持的。

    8. 背景总结

    | 属性 | 作用 | 值 | | —- | —- | —- | | background-color | 背景颜色 | 预定义的颜色值/十六进制/RGB代码 | | background-image | 背景图片 | url(图片路径) | | background-repeat | 是否平铺 | repeat/no-repeat/repeat-x/repeat-y | | background-position | 背景位置 | length/position 分别是x 和 y坐标, 切记 如果有 精确数值单位,则必须按照先X 后Y 的写法 | | background-attachment | 背景固定还是滚动 | scroll/fixed | | 背景简写 | 更简单 | 背景颜色 背景图片地址 背景平铺 背景滚动 背景位置; 他们没有顺序 | | 背景透明 | 让盒子半透明 | background: rgba(0,0,0,0.3); 后面必须是 4个值 |