css2 中的背景(background)

概述

CSS2 中有5个主要的背景(background)属性,它们是:

* margin-bottom:0px; padding-top:0px; padding-bottom:10px; padding-left:30px; border:0px; list-style:none; word-wrap:normal; word-break:normal; line-height:1.8; color:rgb(51,51,51); font-family:微软雅黑,helvetica,Arial">* background-image: 引用图片作为背景。

* background-position: 指定元素背景图片的位置。

* background-repeat: 决定是否重复背景图片。

* background-attachment: 决定背景图是否随页面滚动。

这些属性可以全部合并为一个缩写属性: background。需要注意的一个要点是背景占据元素的所有内容区域,包括 padding 和 border,但是不包括元素的 margin。它在 Firefox, Safari ,Opera 以及 IE8 中工作正常,但是 IE6 和 IE7 中,background 没把 border 计算在内。

Background does not extend to the borders in IE7 and IE6.

基本属性

背景色(background-color)

background-color 属性用纯色来填充背景。有许多方式指定这个颜色,以下方式都得到相同的结果。

background-color: blue;
background-color: rgb(0, 0, 255);
background-color: #0000ff;

background-color 也可被设置为透明(transparent),这会使得其下的元素可见。

背景图(background-image)

background-image 属性允许指定一个图片展示在背景中。可以和 background-color 连用,因此如果图片不重复地话,图片覆盖不到地地方都会被背景色填充。代码很简单,只需要记住,路径是相对于样式表的,因此以下的代码中,图片和样式表是在同一个目录中的。

background-image: url(image.jpg);

但是如果图片在一个名为 images 的子目录中,就应该是:

background-image: url(images/image.jpg);

糖伴西红柿:使用 ../ 表示上一级目录,比如 background-image: url(../images/image.jpg); 表示图片位于样式表的上级目录中的 images 子目录中。有点绕,不过这个大家应该都知道了,我就不详说了。前端观察 版权所有,转载请保留链接。

背景平铺(background-repeat)

设置背景图片时,默认把图片在水平和垂直方向平铺以铺满整个元素。这也许是你需要的,但是有时会希望图片只出现一次,或者只在一个方向平铺。以下为可能的设置值和结果:

background-repeat: repeat; 
background-repeat: no-repeat; 
background-repeat: repeat-x; 
background-repeat: repeat-y; 
background-repeat: inherit; 

背景定位(background-position)

background-position 属性用来控制背景图片在元素中的位置。技巧是,实际上指定的是图片左上角相对于元素左上角的位置。
下面的例子中,设置了一个背景图片并且用 background-position 属性来控制它的位置,同时也设置了 background-repeat 为 no-repeat。计量单位是像素。第一个数字表示 x 轴(水平)位置,第二个是 y 轴(垂直) 位置。

background-position: 0 0; 
 

background-position: 75px 0;
 

background-position: -75px 0;
 

background-position: 0 100px;

posted on 2017-06-25 21:21  静悄悄来,静悄悄走  阅读(256)  评论(0编辑  收藏  举报

导航