CSS背景重复方式属性——background-repeat

background-repeat也是相当常用的属性,因为你在写背景图时,通常都会加个no-repeat,就像这样: background: url('../images/bg.jpg') no-repeat center; 其中的no-repeat就相当于单独设置background-repeat: no-repeat,很常用,就是为了不让背景图重复平铺,因为默认是横向和纵向都会平铺的。 接下来,我将具体讲讲background-repeat的几个属性值。 一、repeat、repeat-x、repeat-y 1. repeat 默认值,横向和纵向平铺,但平铺最终的效果还跟background-position有关。例如: ① 根据左上角定位 background-position: left top; background-repeat: repeat; 结果如下: background-position: left top ② 居中定位 background-position: center; background-repeat: repeat; 结果如下: background-position: center 现在明白了吧,其实就是先定好位,然后再向两个方向延伸,这与书写顺序半毛钱关系都没有,不信你顺序换下也是一样的。 2. repeat-x、repeat-y 横向平铺与纵向平铺,平铺方式与repeat一样,先定位再平铺。 二、no-repeat 不平铺,最为常用,因为大多数情况我们都不希望背景重复。 background-position: center; background-repeat: no-repeat; background-repeat: no-repeat 三、space CSS3新增,当背景图片不能以整数次平铺时,会用空白间隙均匀填充在图片周围,图片不缩放。 例如: background-position: center; background-repeat: space; background-repeat: space 你会发现,background-position: center好像并没有什么用嘛!是的,当某个方向上能平铺多张背景图时,background-position不生效,但是一旦某个方向上只能平铺一张背景图时,background-position的作用就来了,此时就是background-position说了算! 例如,同样大小的盒子,同样的样式,我们给图片放大一点,让其在横向只能平铺一张,但纵向能平铺两张,看看效果。 background-repeat: space 完美!横向background-position生效了,图片居中了,纵向则继续按照background-repeat: space方式进行。 四、round CSS3新增,当背景图片不能以整数次平铺时,会根据情况缩放图片。 它其实跟background-repeat: repeat很像,因为它不像space那样会留白,而是紧密平铺,但是与repeat不同的是,它会通过缩放变形的方式让纵横两个方向上正好平铺满整数个图片(但是并不一定每张图都完整显示,后面会讲到),例如: background-position: left top; background-repeat: round; background-repeat: round 此时的background-position: left top是起作用的,因为图片是从左上角开始平铺的,但是如果是居中定位呢? background-position: center; background-repeat: round; background-repeat: round 看到了吗?background-position: center同样是生效的,它会先居中定位,然后再进行变形处理以让纵横两个方向上正好平铺满整数个图片,此时周边的图片会被裁剪,但是被裁剪的图片合起来还会是一张完整的图片。 五、两个值 前面都是讲单个值的情况,事实上,background-repeat也可以有两个值,第一个代表横向,第二个代表纵向,前面的值(repeat-x和repeat-y除外)都可以作为两个值中的其中一个。例如: background-position: center; background-repeat: space round; background-repeat: space round; 相关推荐 CSS背景定位属性——background-position CSS3背景裁切属性——background-clip 重点总结 ① background-repeat: space平铺的图片之间可能产生间隙,每个方向上的间隙都是均匀的,但前提是该方向上存在多张图片,若只有一张则按照background-position的取值显示 ② background-repeat: round平铺方式与background-repeat: repeat极为相似,只不过round会使图片缩放变形以正好填充整数张图片 ③ background-repeat也可以有两个值,分别代表横向和纵向效果

发表评论 (审核通过后显示评论):

昵称:
邮箱:
内容: