background一共有8个属性,css2.1中5个,css3中加了3个。
一、background版本属性
css 2.1
- background-color: 背景颜色
- background-image: 背景图片
- background-repeat: 重复背景图片
- background-attachment: 是否固定或者随着页面的其余部分滚动
- background-position: 背景图片的位置
css 3
- background-size: 背景的尺寸
- background-origin: 背景图片定位区域
- background-clip: 背景图片绘制区域
background的可以简写为 :
.bg{
background : [background-color] [background-image] [background-repeat] [background-attachment] [background-position] / [background-size] [background-origin] [background-clip]
}
二、属性详情
1. background-color
背景颜色 支持多种类型
- color_name 规定颜色值为颜色名称的背景颜色(比如 red)。
- hex_number 规定颜色值为十六进制值的背景颜色(比如 #ff0000)。
- rgb_number 规定颜色值为 rgb 代码的背景颜色(比如 rgb(255,0,0))。
- transparent 默认值。背景颜色为透明。
- inherit 规定应该从父元素继承背景颜色。
.div1{
background-color:blue;
}
.div2{
background-color:#0000ff;
}
.div3{
background-color:rgb(0,0,255);
}
2. background-image
背景图片 尽量用引号包起来
.div1{
/** 能识别 **/
background-image: url(http://xxxxxxxxx123.jpg);
/** 识别不了 **/
background-image: url(http://xxxxxxxxx-(1)-600x600.jpg);
/** 加了引号 能识别 **/
background-image: url('http://xxxxxxxxx-(1)-600x600.jpg');
}
3. background-repeat
重复图片
- repeat 默认。背景图像将在垂直方向和水平方向重复。
- repeat-x 背景图像将在水平方向重复。
- repeat-y 背景图像将在垂直方向重复。
- no-repeat 背景图像将仅显示一次。
- inherit 规定应该从父元素继承
background-repeat
属性的设置。
.div1{
background-repeat: repeat|repeat-x|repeat-y|no-repeat|inherit;
}
4. background-attachment
滚动或者固定背景
- scroll 默认值。背景图像会随着页面其余部分的滚动而移动。
- fixed 当页面的其余部分滚动时,背景图像不会移动。
- inherit 规定应该从父元素继承
background-attachment
属性的设置。
.div1{
background-attachment:scroll|fixed|inherit;
}
5. background-position
图片位置 支持3中类型: 百分比,单位,英文关键字。三种类型能混合着写
默认值为 0% 0%;
5.1 百分比
第一个值是水平位置,第二个值是垂直位置。
左上角是 0% 0%。右下角是 100% 100%。
如果仅定义一个值,另外一个为50%。
.div1{
background-position:50%;
}
5.2 单位
可以是px或其他单位。
第一个值是水平位置,第二个值是垂直位置。
左上角是 0 0。
如果仅定义一个值,另外一个为50%。
.div1{
background-position:10px 20px;
}
5.3 英文关键字
如果仅定义了一个关键字,另外一个为center
值: center top bottom left right
.div1{
background-position: center|top|bottom|left|right center|top|bottom|left|right;
}
6. background-size
背景大小 有四种类型
.div1{
background-size: auto auto|100% 100%|contain|cover;
}
6.1 值
设置背景图像的高度和宽度。
第一个值设置宽度,第二个值设置高度。
如果只设置一个值,则第二个值会被设置为 "auto"。
6.2 百分比
以父元素的百分比来设置背景图像的宽度和高度。
第一个值设置宽度,第二个值设置高度。
如果只设置一个值,则第二个值会被设置为 "auto"。
6.3 cover
把背景图像扩展至足够大,以使背景图像完全覆盖背景区域。
背景图像的某些部分也许无法显示在背景定位区域中。
6.4 contain
把图像图像扩展至最大尺寸,以使其宽度和高度完全适应内容区域。
7. background-origin
背景的相对定位
背景图像的 background-attachment
属性为 fixed
,则该属性没有效果。
- padding-box 背景图像相对于内边距框来定位。
- border-box 背景图像相对于边框盒来定位。
- content-box 背景图像相对于内容框来定位。
div1{
background-origin: padding-box|border-box|content-box;
}
8. background-clip
规定背景的绘制区域
- border-box 背景被裁剪到边框盒。
- padding-box 背景被裁剪到内边距框。
- content-box 背景被裁剪到内容框。
div1{
background-clip:padding-box|border-box|content-box;
}