一、背景
1、纯色背景
CSS 允许应用纯色作为背景,也允许使用背景图像创建相当复杂的效果。
<html>
<head>
<style type="text/css">
body {background-color: white}
h1 {background-color: pink}
h2 {background-color: transparent}
p {background-color: blue}
p.no2 {background-color: gray; padding: 20px;}
</style>
</head>
<body>
<h1>这是标题 1</h1>
<h2>这是标题 2</h2>
<p>这是段落</p>
<p class="no2">这个段落设置了内边距。</p>
</body>
</html>
可以为所有元素设置背景色,这包括 body 一直到 em 和 a 等行内元素。
background-color 不能继承,其默认值是 transparent。transparent 有“透明”之意。也就是说,如果一个元素没有指定背景色,那么背景就是透明的,这样其祖先元素的背景才能可见。
2、图像背景
要把图像放入背景,需要使用 background-image 属性。background-image 属性的默认值是 none,表示背景上没有放置任何图像。
如果需要设置一个背景图像,必须为这个属性设置一个 URL 值:
<html>
<head>
<style type="text/css">
body {background-image:url(/i/eg_bg_04.gif);}
</style>
</head>
<body></body>
</html>
背景重复
如果需要在页面上对背景图像进行平铺,可以使用 background-repeat 属性。
属性值 repeat 导致图像在水平垂直方向上都平铺,就像以往背景图像的通常做法一样。repeat-x 和 repeat-y 分别导致图像只在水平或垂直方向上重复,no-repeat 则不允许图像在任何方向上平铺。
背景定位
可以利用 background-position 属性改变图像在背景中的位置。
下面的例子在 body 元素中将一个背景图像居中放置:
body
{
background-image:url('/i/eg_bg_03.gif');
background-repeat:no-repeat;
background-position:center;
}
背景关联
如果文档比较长,那么当文档向下滚动时,背景图像也会随之滚动。当文档滚动到超过图像的位置时,图像就会消失。
可以通过 background-attachment 属性防止这种滚动。通过这个属性,可以声明图像相对于可视区是固定的(fixed),因此不会受到滚动的影响
CSS 背景属性
属性 | 描述 |
---|---|
background | 简写属性,作用是将背景属性设置在一个声明中。 |
background-attachment | 背景图像是否固定或者随着页面的其余部分滚动。 |
background-color | 设置元素的背景颜色。 |
background-image | 把图像设置为背景。 |
background-position | 设置背景图像的起始位置。 |
background-repeat | 设置背景图像是否及如何重复。 |