本节主要关注背景如何展示。

background

在一个声明中设置所有背景属性。

试一试

div{
  background: #00FF00 url(bgimage.gif) no-repeat fixed top;
}

可以按顺序设置如下属性:

  • background-color
  • background-position
  • background-size
  • background-repeat
  • background-origin
  • background-clip
  • background-attachment
  • background-image
background 值作用CSS版本
background-color 规定要使用的背景颜色。1
background-position 规定背景图像的位置。1
background-size 规定背景图片的尺寸。3
background-repeat 规定如何重复背景图像。1
background-origin 规定背景图片的定位区域。3
background-clip 规定背景的绘制区域。3
background-attachment 规定背景图像是否固定或者随着页面的其余部分滚动。1
background-image 规定要使用的背景图像。1
inherit 规定应该从父元素继承 background 属性的设置。1

background-color

设置背景颜色。

div{
  background-color:#00ff00;
}
background-color 值作用
color_name 规定颜色值为颜色名称的背景颜色(比如 red)。
hex_number 规定颜色值为十六进制值的背景颜色(比如 #ff0000)。
rgb_number 规定颜色值为 rgb 代码的背景颜色(比如 rgb(255,0,0))。
transparent 默认。背景颜色为透明。
inherit 规定应该从父元素继承 background-color 属性的设置。

background-image

设置背景图片。

div{
  background-image:url(bgimage.gif);
}
background-image 值作用
url('URL') 指向图像的路径。
none 默认值。不显示背景图像。
inherit 规定应该从父元素继承 background-image 属性的设置。

background-clip

规定背景的绘制区域。

div{
  background-clip:content-box;
}
background-clip 值作用
border-box 背景被裁剪到边框盒。
padding-box 背景被裁剪到内边距框。
content-box 背景被裁剪到内容框。

background-repeat

设置如何重复背景图像。

div{
  background-repeat: repeat-y;
}
background-repeat 值作用
repeat 默认。背景图像将在垂直方向和水平方向重复。
repeat-x 背景图像将在水平方向重复。
repeat-y 背景图像将在垂直方向重复。
no-repeat 背景图像将仅显示一次。
inherit 规定应该从父元素继承 background-repeat 属性的设置。

background-size

规定背景图像的尺寸。

div{
  background-size:80px 60px;
}
background-size 值作用
length设置背景图像的高度和宽度。 第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。
percentage 以父元素的百分比来设置背景图像的宽度和高度。 第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。
cover 把背景图像扩展至足够大,以使背景图像完全覆盖背景区域。 背景图像的某些部分也许无法显示在背景定位区域中。
contain把图像图像扩展至最大尺寸,以使其宽度和高度完全适应内容区域。