De forma predeterminada, la propiedad imagen de fondo
repite una imagen tanto horizontal como verticalmente.
Algunas imágenes deben repetirse sólo horizontal o verticalmente, o se verán extrañas, como esta:
body
{
background-image: url("gradient_bg.png");
}
Pruébelo usted mismo →
<!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 la imagen de arriba se repite solo horizontalmente (fondo-repeat: repetir-x;
), el fondo se verá mejor:
body
{
background-image: url("gradient_bg.png");
background-repeat: repeat-x;
}
Pruébelo usted mismo →
<!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>
Consejo: Para repetir una imagen verticalmente, configure fondo-repetir: repetir-y;
Mostrar la imagen de fondo solo una vez también se especifica mediante la propiedad background-repeat
:
Muestra la imagen de fondo solo una vez:
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
}
Pruébelo usted mismo →
<!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>
En el ejemplo anterior, la imagen de fondo se coloca en el mismo lugar que el texto. Queremos cambiar la posición de la imagen, para que no alterar demasiado el texto.
La propiedad posición-fondo
se utiliza para especifique la posición de la imagen de fondo.
Coloque la imagen de fondo en la esquina superior derecha:
body
{
background-image: url("img_tree.png");
background-repeat: no-repeat;
background-position: right top;
}
Pruébelo usted mismo →
<!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>
Establece la posición inicial de una imagen de fondo.
Establece cómo se repetirá una imagen de fondo