CSS 背景图像重复


目录

    显示目录


CSS 背景重复

默认情况下,background-image 属性会在水平和垂直方向上重复图像。

有些图像只能水平或垂直重复,否则它们看起来会很奇怪,如下所示:

例子

body
{
  background-image: url("gradient_bg.png");
}

自己尝试一下→

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("gradient_bg.png");
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Strange background image...</p>

</body>
</html>


如果上面的图像仅水平重复(background-repeat:repeat-x;),背景将看起来 更好的:

例子

body
{
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("gradient_bg.png");
  background-repeat: repeat-x;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Here, a background image is repeated only horizontally!</p>

</body>
</html>


提示:要垂直重复图像,请设置background-repeat:repeat-y;


CSS 背景重复:不重复

仅显示一次背景图像也由 background-repeat 属性指定:

例子

仅显示背景图像一次:

body
{
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>W3Schools background image example.</p>
<p>The background image only shows once, but it is disturbing the reader!</p>

</body>
</html>


在上面的示例中,背景图像放置在与文本相同的位置。我们想要改变图像的位置,这样它就不会 过多干扰文本。


CSS 背景位置

background-position 属性用于 指定背景图像的位置。

例子

将背景图像放置在右上角:

body
{
   
background-image: url("img_tree.png");
   
background-repeat: no-repeat;
   
background-position: right top;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-image: url("img_tree.png");
  background-repeat: no-repeat;
  background-position: right top;
  margin-right: 200px;
}
</style>
</head>
<body>

<h1>Hello World!</h1>
<p>Here, the background image is only shown once. In addition it is positioned away from the text.</p>
<p>In this example we have also added a margin on the right side, so that the background image will not disturb the text.</p>

</body>
</html>



CSS 背景重复和位置属性

background-position

设置背景图像的起始位置

background-repeat

设置背景图像的重复方式