给元素添加背景也是比较重要的存在.
有多个属性来搞定背景.
一. background-color
添加背景色
颜色值和前面讲的一样.
还接收一个透明色: background-color: transparent;
天天用, 不多说了.
二. background-image
用一张图片给元素做背景.
他的值是一个url.
background-image: url("1.jpg");
url
的写法也支持相对路径和绝对路径.
三. background-repeat
如果图片小于元素的尺寸了, 则单张图片是无法完全覆盖整个元素的.
这个属性来设置如果处理不能覆盖的地方, 是否平铺图片.
<style>
div{
width: 800px;
height: 400px;
margin-bottom: 10px;
background-color: pink;
background-image: url("2.jpg");
}
div.two{
background-repeat: no-repeat;
}
</style>
<div class="one"></div>
<div class="two"></div>
说明:
默认值是平铺
no-repeat
不平铺.水平平铺:
repeat-x
垂直平铺:
repeat-y
四. background-position
背景定位.
背景图片默认是从元素的左上角(0,0)
开始排列.
通过这个属性可以设置背景图片在水平和垂直方向的偏移.
正的向上和向下, 负的向左和向上
background-position: 100px 100px;
说明:
也可以使用关键字:
left, top, right, bottom, center
例如: 右上角
background-position : right top;
关键字没有顺序. 所以右上也可以:background-position : top right;
如果只有一个关键字, 则另一个是
center
.background-position : right;
则垂直方向为center
.background-position : top;
则水平方向为center
.也可以使用百分比.
允许负值
这个属性当使用精灵图片的时候非常有用.
五. 简写属性: background
前面的属性一个个的写起来太麻烦了, CSS
的提供了简写属性background
background : red url("1.jpg") no-repeat ceneter center;