背景颜色(background-color)

  • 语法:
  1. background-color:颜色值; 默认值是 transparent(透明的)

背景图片(background-image)

  • 语法:
background-image : none | url (url)

例如:

background-image : url(images/demo.png);

注意:图片的url地址没有加引号“”

背景平铺(background-repeat)

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

背景位置(background-position)重点

  1. 语法:
background-position : position || position 

background-position : length || length
参数
position top | center | bottom | left | center | right 方位名词
length 百分数 | 由浮点数字和单位标识符组成的长度值
  1. 注意:
  • 必须先设置background-image的属性。
  • position 后面是x坐标和y坐标。 可以使用方位名词或者精确单位。
  • 如果指定的两个值都是方位名词,则两个值前后顺序无关,比如left top和top left效果一致
  • 如果只指定了一个方位名词,另一个值默认居中对齐(center)。
  • 如果 position 后面是精确坐标, 那么第一个肯定是 x 坐标,第二的一定是 y 坐标。
  • 如果只指定一个数值,那该数值一定是 x 坐标,另一个默认垂直居中
  • 如果指定的两个值是精确单位和方位名词混合使用,则第一个值是x坐标,第二个值是y坐标

坐标原点在页面左上角,像这样:
iShot2020-05-11下午07.56.05.png

  1. 设置页面超大背景图片,常用:
    background-position : center top;
    

背景附着(background-attachment)

背景附着就是设置背景图片是滚动的还是固定的。其语法为:

background-attachment : scroll | fixed
属性值 作用
scroll 背景图像是随对象内容滚动
fixed 背景图像固定

背景图片尺寸(background-size)

background-size 规定背景图像的尺寸,其语法为:

background-size: length|percentage|cover|contain;
属性值 描述
length 第一个值设置宽度,第二个值设置高度。
如果只设置一个值,则第二个值会被设置为 “auto”。
percentage 以父元素的百分比来设置背景图片的宽度和高度。
cover 把背景图像扩展至足够大,以使背景图像完全覆盖背景区域。
contain 把图像扩展至最大尺寸,以使其宽度和高度完全适应内容区域。

背景透明(CSS3)

语法:

background: rgba(0, 0, 0, 0.3);
  • 最后一个参数是alpha透明度,其取值范围在 0~1 之间。
  • 我们习惯把 0.3 的 0 省略掉,可以这样写 background: rgba(0, 0, 0, .3);

综合设置背景样式(background)

background属性的值的书写顺序官方并没有强制标准。为了可读性,建议按如下写:

background: 背景颜色 背景图片地址 背景平铺 背景滚动 背景位置;

总结

属性 作用
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); 后面必须是 4个值

扩展:背景图片一般用于小图标 或者 网页超大背景图片。大多数情况使用插入图片,如,产品展示。