默认情况下,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;
仅显示一次背景图像也由 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>
在上面的示例中,背景图像放置在与文本相同的位置。我们想要改变图像的位置,这样它就不会 过多干扰文本。
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>
设置背景图像的起始位置
设置背景图像的重复方式