背景色
p {background-color: gray; padding: 20px;}
可以为所有元素设置背景色,这包括 body 一直到 em 和 a 等行内元素。
background-color 不能继承,其默认值是 transparent。transparent 有“透明”之意。也就是说,如果一个元素没有指定背景色,那么背景就是透明的,这样其祖先元素的背景才能可见。
背景图像
要把图像放入背景,需要使用 background-image 属性。background-image 属性的默认值是 none,表示背景上没有放置任何图像。
body {background-image: url(/i/eg_bg_04.gif);}
背景重复
如果需要在页面上对背景图像进行平铺,可以使用 background-repeat 属性。
属性值 repeat 导致图像在水平垂直方向上都平铺,就像以往背景图像的通常做法一样。repeat-x 和 repeat-y 分别导致图像只在水平或垂直方向上重复,no-repeat 则不允许图像在任何方向上平铺。
body
{
background-image: url(/i/eg_bg_03.gif);
background-repeat: repeat-y;
}
背景定位
可以利用 background-position 属性改变图像在背景中的位置。
(1)关键字
p
{
background-image:url('bgimg.gif');
background-repeat:no-repeat;
background-position:top; // center bottom right left
}
(2)百分数值
body
{
background-image:url('/i/eg_bg_03.gif');
background-repeat:no-repeat;
background-position:50% 50%;
}
(3)长度值
body
{
background-image:url('/i/eg_bg_03.gif');
background-repeat:no-repeat;
background-position:50px 100px;
}
背景关联
如果文档比较长,那么当文档向下滚动时,背景图像也会随之滚动。当文档滚动到超过图像的位置时,图像就会消失。
您可以通过 background-attachment 属性防止这种滚动。通过这个属性,可以声明图像相对于可视区是固定的(fixed),因此不会受到滚动的影响:
body
{
background-image:url(/i/eg_bg_02.gif);
background-repeat:no-repeat;
background-attachment:fixed
}
background-attachment 属性的默认值是 scroll,也就是说,在默认的情况下,背景会随文档滚动。