Par défaut, la propriété background-image répète une image horizontalement et verticalement.
Certaines images doivent être répétées uniquement horizontalement ou verticalement, sinon elles auront un aspect étrange, comme ceci :
body
{
background-image: url("gradient_bg.png");
}Essayez-le vous-même →
<!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>
Si l'image ci-dessus est répétée uniquement horizontalement (background-repeat: repeat-x;), l'arrière-plan ressemblera à mieux:
body
{
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}Essayez-le vous-même →
<!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>
Conseil : Pour répéter une image verticalement, définissez background-repeat: répétition-y;
Afficher l'image d'arrière-plan une seule fois est également spécifié par la propriété background-repeat :
Afficher l'image d'arrière-plan une seule fois :
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
}Essayez-le vous-même →
<!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>
Dans l’exemple ci-dessus, l’image de fond est placée au même endroit que le texte. Nous voulons changer la position de l'image, pour qu'elle ne déranger trop le texte.
La propriété background-position est utilisée pour spécifier la position de l'image d'arrière-plan.
Positionnez l'image d'arrière-plan dans le coin supérieur droit :
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}Essayez-le vous-même →
<!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>
Définit la position de départ d'une image d'arrière-plan
Définit la manière dont une image d'arrière-plan sera répétée