background是一个复合属性,可以用用来设置背景颜色。背景图片等操作;
背景颜色(bgc)background-color
用来设置元素的背景颜色,取值可以是预定义的英文,16进制取值,rgb取值;
/* 预定义英文 */ background-color: red; /* 16进制 */ background-color: #f00; /* rgb取值 */ background-color: rgb(255,0,0);
背景图(bgi) background-image
用来设置元素的背景图片,必须要配合url属性值获取背景图片的路径;
background-image: url(./img/gAT.gif);
背景图的平铺方式(bgr)background-repeat
插入背景图以后背景图默认是平铺的,我们可以通过background-repeat设置不同的取值实现背景图是否平铺;
01、取值为repeat,是默认的取值,背景图会平铺;
background-repeat: repeat;
02、取值为no-repeat,设置背景图不平铺;
background-repeat: no-repeat;
03、可以单独设置水平或者垂直方的单一平铺,取值为repeat-x或者repeat-y
/* 水平方向平铺 */ background-repeat: repeat-x; /* 垂直方向平铺 */ background-repeat: repeat-y;
背景位置设置(bgp)background-position
基本语法
设置背景图在元素中的位置
默认取值为0,0,表示背景图就在元素的左上角;
background-position: 0 0;
取值为方位名词(了解)
水平方向:left、center、right;
垂直方向:top、center、bottom;
/* 左下角 */ background-position: left bottom; /* 左上角 */ background-position: left top; /* 右下角 */ background-position: right bottom; /* 右上角 */ background-position: right top; /* 顶部和底部水平居中 */ background-position: center top; background-position: center bottom; /* 左侧和右侧垂直居中 */ background-position: left center; background-position: right center; /* 水平垂直居中 */ background-position: center center; /* 简写 */ background-position: center;
取值为实际像素
取值为两个实际像素,让背景图在我们预定义好的位置显示;
background-position: 100px 100px;
如果取值为一个值,那么这个值是表示左右的水平位置,垂直方向的位置默认居中显示;
background-position: 80px;
取值为百分比
取值为百分计算的值是按照父级盒子宽高计算的;
background-position: 50% 50%;
如果取值为一个值,那么这个值是表示左右的水平位置,垂直方向的位置默认居中显示;
背景固定(bga)background-attachment
设置背景图片是否跟随内容滚动;
默认取值scroll滚动
background-attachment: scroll;
不滚动 fixed
background-attachment: fixed;
背景属性综合写法1(记住)
基本语法
背景颜色 背景图片地址 背景平铺 背景图像滚动 背景图片位置;
注意:01、属性值没有书写顺序,没有的属性可以省略不写; 02、属性值和属性值之间用空格隔开;
/* background-color: magenta; */ /* background-image: url(./img/icon.png); */ /* background-repeat: no-repeat; */ /* background-position: 5px center; */ /* background: 背景颜色 背景图片地址 背景平铺 背景图像滚动 背景图片位置; */ background: magenta url(./img/icon.png) no-repeat 5px center;
背景尺寸设置(bgs)background-size
设置背景图的尺寸大小;
取值为cover(常用)
背景图等比缩放,一直到铺满整个盒子
background-size: cover;
注意:该属性取值如果背景图和盒子比例不一致。可能会导致背景图过大超出盒子显示不全;
取值为contain
背景图等比缩放,直到背景图的宽或者高和盒子一致就停止缩放
background-size: contain;
注意:该属性取值如果背景图和盒子比例不一致可能会导致背景图不会完全铺满盒子;
取值为实际像素大小(移动端小图标常用)
设置背景图大小固定
背景颜色透明rgba
我们可以设置背景颜色的透明度从而实现透明效果;
语法: rgba(red, green, blue, alpha)
alpha取值为0-1之间,0表示完全透明,1表示不透明,之间的数字表示透明的程度
background-color: rgba(0,0,0,.5);
注意:rgba只能设置背景颜色透明不会影响盒子里面的内容透明;
五、盒子透明opacity
语法: opacity: 透明值;
opacity 设置盒子的透明,取值为0-1之间,0表示完全透明,1表示不透明,之间的小数表示透明的程度
opacity: .5;
注意:用opacity 设置透明,不仅让背景颜色透明,也会影响盒子里面的内容也跟着透明,所以我们不建议使用,后期在制作css3的动画时会用到;