一、background属性可以设置一个元素的背景样式,当然前提是这个元素有具体的宽高值。
先来一个简单的背景设置:
#show-box {
width: 800px;
height: 500px;
background: #000;
background-image: url(image url);
}
</style>
这里只是简单的设置了颜色和背景贴图。
下面让我们来看一下官方的background的属性:
语法格式:
background: color position size repeat origin clip attachment image;
注意:如果同时设置了“position”和“size”两个属性,应该用左斜杠“/”,而不是用空格把两个参数值隔开:“position/size”。
background: url("img.jpg") center center/100% 100% no-repeat;
1.color:背景颜色值。这个属性会把整个元素添加颜色,而且处于最底层(在有背景图片的情况下就可以看出)。
可选值:默认是透明,其他值可以通过查看“CSS颜色值表”来设置。
<style>
#show-box {
width: 180px;
height: 180px;
border: 20px dashed #000;
background-color: #000000;
background-color: blue;
background-color: rgb(255, 255, 255);
background-color: rgba(255, 255, 255, 0.8);
}
</style>
2.position:背景图片的定位。如果没有图片设置,那么这个属性不起效果。
可选值:两个参数,水平位置和垂直位置。如果只有一个值,第二个值为“center”。
默认值是元素的左上顶角。可以使用位置关键字(top,right,bottom,left,center)。百分比(以元素大小为基值)。像素值。
<style>
#show-box {
width: 180px;
height: 180px;
border: 20px dashed #000;
background-position: center;
background-position: center top;
background-position: 0 100px;
background-position: 10% 20%;
}
</style>
3.size:图片尺寸。应用于图片。
可选值:两个数值,如果只有一个值,第二个值为auto。
默认是图片自身大小。可以使用像素值,百分百(以元素大小为基值)。
cover:等比例缩放图片,覆盖这个元素。类似与windows中桌面背景的“填充”。
contain:等比例缩放图片,适应元素的宽或者高。类似于windows中桌面背景的“适应”。
4.repeat:平铺方式。
repeat:完全平铺,复制图片把整个元素填满。(默认)
repeat-x:水平平铺,在水平方向复制并平铺。
repeat-y:垂直平铺,在垂直方向复制并平铺。
no-repeat:不平铺,只使用一张图片。
5.origin:背景的参考区域。
可选值:border-box,padding-box,content-box。
6.clip:背景的可视区域。
可选值:border-box,padding-box,content-box。
1.origin:border-box;clip:border-box;
<style>
#show-box {
width: 180px;
height: 180px;
margin: 20px;
padding: 20px;
border: 20px dashed #000;
background: url("img.jpg") no-repeat border-box border-box;
}
</style>
2.origin:padding-box;clip:border-box;
<style>
#show-box {
width: 180px;
height: 180px;
margin: 20px;
padding: 20px;
border: 20px dashed #000;
background: url("img.jpg") no-repeat padding-box border-box;
}
</style>
3.origin:content-box;clip:border-box;
<style>
#show-box {
width: 180px;
height: 180px;
margin: 20px;
padding: 20px;
border: 20px dashed #000;
background: url("img.jpg") no-repeat content-box border-box;
}
</style>
4.origin:border-box;clip:content-box;
<style>
#show-box {
width: 180px;
height: 180px;
margin: 20px;
padding: 20px;
border: 20px dashed #000;
background: url("img.jpg") no-repeat border-box content-box;
}
</style>
可以看出,origin设置的是位置,clip则会根据区域裁剪出背景图片。
7.attachment:设置背景图像是否固定或者随着页面的其余部分滚动。
默认值是scroll:背景图片随页面的其余部分滚动。fixed:背景图像是固定的。