CSS 可以为标签添加背景颜色和背景图片,背景属性如下表:
属性名称 | 含义 |
---|---|
background-color | 背景颜色 |
background-image | 背景图片地址 |
background-repeat | 是否平铺 |
background-position | 背景位置 |
background-attachment | 背景固定还是滚动 |
background:背景颜色 背景图片地址 背景平铺 背景滚动 背景位置 | 背景的合写(复合属性) |
背景色
语法:
background-color: 颜色;
背景图片(image)
语法:
background-image : none | url (url)
参数:
-
none : 无背景图(默认的)
-
url : 使用绝对或相对地址指定背景图像
背景平铺(repeat)
语法:
background-repeat : repeat | no-repeat | repeat-x | repeat-y
参数:
-
repeat : 背景图像在纵向和横向上平铺(默认值)
-
no-repeat : 背景图像不平铺
-
repeat-x : 背景图像在横向上平铺
-
repeat-y : 背景图像在纵向平铺
背景位置(position)
语法:
background-position : x坐标 y坐标
参数:
-
-
坐标值 : 百分数 | 固定值 | top | center | bottom | left | center | right
-
如果和精确单位和方位名字混合使用,则必须是x坐标在前,y坐标后面
-
比如 background-position: 15px top; 则 15px 一定是 x坐标 top是 y坐标。
背景附着
语法:
background-attachment : scroll | fixed
参数:
-
scroll : 背景图像是随对象内容滚动
-
fixed : 背景图像固定
-
-
设置或检索背景图像是随对象内容滚动还是固定的。
语法:
background:背景颜色 背景图片地址 背景平铺 背景滚动 背景位置;
示例:
<style>
body {
background: #eee url(images/cat.png) no-repeat fixed center center;
}
</style>
背景缩放(CSS3)
概念:
-
通过background-size设置背景图片的尺寸,就像我们设置img的尺寸一样。
语法:
background-size:参数;
参数:
-
可以设置长度单位(px)或百分比
-
设置为cover时,会自动调整缩放比例,保证图片始终填充满背景区域,如有溢出部分则会被隐藏。
-
设置为contain,会自动调整缩放比例,保证图片始终完整显示在背景区域,不会溢出。