CSS - background-repeat 属性



CSS background-repeat 属性控制背景图片的重复方式。图片可以在水平和垂直方向上重复,也可以不重复。

语法

background-repeat: repeat | repeat-x | repeat-y | no-repeat | space | round | initial | inherit;

属性值

描述
repeat 背景图片在水平和垂直方向上都重复。默认值。
repeat-x 背景图片在水平方向上重复。
repeat-y 背景图片在垂直方向上重复。
no-repeat 背景图片不重复。
space 尽可能多地重复图片,但不剪裁。第一个和最后一个图片固定在元素的两侧,空白区域均匀分布在图片之间。
round 重复背景图片并将其压缩或拉伸以填充空白区域。
initial 将属性设置为其初始值。
inherit 从父元素继承该属性。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

CSS 背景重复属性示例

下面介绍了使用不同值的 background-repeat 属性的示例。

图片重复

要使背景图片在垂直和水平方向上都重复,我们使用 repeat 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .repeat { background-image: url('/css/images/tutimg.png'); background-repeat: repeat; width: 800px; height: 400px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="repeat"></div> </body> </html>

水平方向图片重复

要使背景图片在水平方向上重复,我们使用 repeat-x 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .repeat-x { background-image: url('/css/images/tutimg.png'); background-repeat: repeat-x; width: 800px; height: 300px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="repeat-x"></div> </body> </html>

垂直方向图片重复

要使背景图片在垂直方向上重复,我们使用 repeat-y 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .repeat-y { background-image: url('/css/images/tutimg.png'); background-repeat: repeat-y; width: 800px; height: 300px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="repeat-y"></div> </body> </html>

阻止图片重复

要阻止背景图片重复,我们使用 no-repeat 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .no-repeat { background-image: url('/css/images/tutimg.png'); background-repeat: no-repeat; width: 800px; height: 300px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="no-repeat"></div> </body> </html>

带间距的图片重复

要使图片重复多次并在它们之间均匀分布空白区域,我们使用 space 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .space { background-image: url('/css/images/tutimg.png'); background-repeat: space; width: 800px; height: 300px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="space"></div> </body> </html>

拉伸以填充空白区域

要使图片重复多次并在它们之间留下少量空白区域,我们使用 round 值。如下例所示。

示例

Open Compiler
<!DOCTYPE html> <html> <head> <style> .round { background-image: url('/css/images/tutimg.png'); background-repeat: round; width: 800px; height: 300px; position: relative; } </style> </head> <body> <h2>CSS background-repeat property</h2> <div class="round"></div> </body> </html>

支持的浏览器

属性 Chrome Edge Firefox Safari Opera
background-repeat 1.0 4.0 1.0 1.0 3.5
css_properties_reference.htm
广告