CSS 允许应用纯色作为背景,也允许使用背景图像创建相当复杂的效果。
背景色
可以使用 background-color 属性为元素设置背景色。这个属性接受任何合法的颜色值。
这条规则把元素的背景设置为灰色:
p {background-color: gray;}如果您希望背景色从元素中的文本向外少有延伸,只需增加一些内边距:
p {background-color: gray; padding: 20px;}可以为所有元素设置背景色,这包括 body 一直到 em 和 a 等行内元素。
body {background-image: url(eg_bg_04.gif);}大多数背景都应用到 body 元素,不过并不仅限于此。
p.flower {background-image: url(eg_bg_03.gif); padding: 20px;}您甚至可以为行内元素设置背景图像,下面的例子为一个链接设置了背景图像:
a.radio {background-image: url(eg_bg_07.gif); padding: 20px;}注意:background-image 也不能继承。事实上,所有背景属性都不能继承。
<html> <head> <style type="text/css"> body {background-image: url(eg_bg_04.gif);} p.flower {background-image: url(eg_bg_03.gif); padding: 20px;} a.radio {background-image: url(eg_bg_07.gif); padding: 20px;} </style> </head> <body> <p class="flower">我是一个段落。<a href="#" class="radio">我是链接。</a></p> <p><b>注释:</b>为了清晰地显示出段落和链接的背景图像,为它们设置了内边距。</p> </body> </html>
body { background-image: url(eg_bg_03.gif); background-repeat: repeat-y; }
body { background-image: url("eg_bg_03.gif"); background-repeat: no-repeat; background-position: center; }注释:为 background-position 属性提供值有很多方法。
p { background-image: url("bgimg.gif"); background-repeat: no-repeat; background-position: top; }
body { background-image: url("eg_bg_03.gif"); background-repeat: no-repeat; background-position: 50% 50%; }注释:这会导致图像适当放置,其中心与其元素的中心对齐。百分数值同时应用于元素和图像:
body { background-image: url("eg_bg_03.gif"); background-repeat: no-repeat; background-position: 66% 33%; }如果只提供一个百分数值,所提供的这个值将用作水平值,垂直值将假设为 50%。
body { background-image: url("eg_bg_03.gif"); background-repeat: no-repeat; background-position: 50px 100px; }注释:图像的左上角将在元素内边距区左上角向右 50 像素、向下 100 像素的位置上。
body { background-image: url(eg_bg_02.gif); background-repeat: no-repeat; background-attachment: fixed }注释:background-attachment 属性的默认值是 scroll,在默认的情况下,背景会随文档滚动。
body { background: #ff0000 url(../i/eg_bg_03.gif) no-repeat fixed center; }注释:本例演示如何使用简写属性来将所有背景属性设置在一个声明之中。
评论