background-image 详解

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

background-image: url(image.jpg); 但是如果图片在一个名为 images 的子目录中,就应该是:

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

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

background-repeat: no-repeat; /* 不平铺。图片只展示一次。 */

background-repeat: repeat-x; /* 水平方向平铺(沿 x 轴) */

background-repeat: repeat-y; /* 垂直方向平铺(沿 y 轴) */

background-repeat: inherit; /* 继承父元素的 background-repeat 属性*/

背景定位(background-position) background-position 属性用来控制背景图片在元素中的位置。

技巧是,实际上指定的是图片左上角相对于元素左上角的位置。 下面的例子中,设置了一个背景图片并且用 background-position 属性来控制它的位置,同时也设置了 background-repeat 为 no-repeat。计量单位是像素。第一个数字表示 x 轴(水平)位置,第二个是 y 轴(垂直) 位置。 /* 例 1: 默认值 */ background-position: 0 0; /* 元素的左上角 */ /* 例 2: 把图片向右移动 */ background-position: 75px 0; /* 例 3: 把图片向左移动 */ background-position: -75px 0; /* 例 4: 把图片向下移动 */ background-position: 0 100px;

posted on 2016-06-18 00:10  web小白菜  阅读(580)  评论(0)    收藏  举报

导航