By default, the background-image
property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like this:
Set the background image for a page:/p>
<!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>
If the image above is repeated only horizontally (background-repeat: repeat-x;
), the background will look better:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
</head>
<body>
<h1>Hello World!</h1>
<p>Here, a background image is repeated only horizontally!</p>
</body>
</html>
The background-position
property is used to specify the position of the background image.
Position the background image in the top-right corner:
<!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>