Standardmäßig wiederholt die Eigenschaft background-image
ein Bild sowohl horizontal als auch vertikal.
Einige Bilder sollten nur horizontal oder vertikal wiederholt werden, sonst sehen sie seltsam aus, wie zum Beispiel:
body
{
background-image: url("gradient_bg.png");
}
Probieren Sie es selbst aus →
<!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>
Wenn das obige Bild nur horizontal wiederholt wird (background-repeat: repeat-x;
), sieht der Hintergrund so aus besser:
body
{
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
Probieren Sie es selbst aus →
<!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>
Tipp: Um ein Bild vertikal zu wiederholen, legen Sie background-repeat: repeat-y;
fest
Dass das Hintergrundbild nur einmal angezeigt wird, wird auch durch die Eigenschaft background-repeat
festgelegt:
Das Hintergrundbild nur einmal anzeigen:
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
Probieren Sie es selbst aus →
<!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>
Im obigen Beispiel wird das Hintergrundbild an derselben Stelle wie der Text platziert. Wir möchten die Position des Bildes ändern, damit dies nicht der Fall ist stören den Text zu sehr.
Die Eigenschaft background-position
wird dazu verwendet Geben Sie die Position des Hintergrundbilds an.
Positionieren Sie das Hintergrundbild in der oberen rechten Ecke:
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Probieren Sie es selbst aus →
<!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>
Legt die Startposition eines Hintergrundbilds fest
Legt fest, wie ein Hintergrundbild wiederholt wird