CSS background-repeat 属性


CSS Background-repeat Property

在CSS中,背景图片通常需要在元素上进行重复平铺,使背景更加丰富和生动。为此,CSS提供了background-repeat属性,可以控制背景图片在水平和垂直方向的重复方式。

语法

background-repeat: repeat | repeat-x | repeat-y | no-repeat | initial | inherit; 
  • repeat:默认值,背景图片在水平和垂直方向重复平铺。
  • repeat-x:背景图片在水平方向重复平铺,垂直方向不重复。
  • repeat-y:背景图片在垂直方向重复平铺,水平方向不重复。
  • no-repeat:背景图片不进行重复平铺,仅显示一次。
  • initial:设置属性为它的默认值。
  • inherit:从父元素继承该属性。

实例展示

background-repeat

div {
    background-image: url("bg_image.png");
    background-repeat: no-repeat;  
    /* do not repeat background image */
    background-position: center center;  
    /* center the background image */
}

此代码块将元素的背景图片居中并仅显示一次。

属性值详解

repeat

默认情况下,当未指定背景图片重复方式时,将自动采用repeat的方式,使背景图片在水平和垂直方向重复平铺到元素的边缘。

div {
    background-image: url("bg_image.png");
    /* repeat background image */
}

repeat-x

使用repeat-x属性值,使背景图片只在水平方向重复平铺,而垂直方向仅显示一次。

div {
    background-image: url("bg_image.png");
    background-repeat: repeat-x;
    /* repeat background image horizontally */
}

repeat-y

使用repeat-y属性值,使背景图片只在垂直方向重复平铺,而水平方向仅显示一次。

div {
    background-image: url("bg_image.png");
    background-repeat: repeat-y;
    /* repeat background image vertically */
}

no-repeat

使用no-repeat属性值,使背景图片仅显示一次,不进行任何重复平铺。

div {
    background-image: url("bg_image.png");
    background-repeat: no-repeat;
    /* do not repeat background image */
}

initial

使用initial属性值,将属性设置为它的默认值。

div {
    background-repeat: initial;
    /* set property to its default value */
}

inherit

使用inherit属性值,从父元素继承该属性。

div {
    background-repeat: inherit;
    /* inherit property from parent */
}

总结

background-repeat属性在CSS中用于控制背景图片在元素上的重复方式,默认值为repeat,背景图片在水平和垂直方向都进行重复平铺,并且可以通过其他属性值调整垂直或水平方向的重复平铺方式。此属性值非常有用,可以使您创建出不同的图案和花纹,来充实网页设计中的背景元素。