Estirar y escalar una imagen CSS en el fondo-solo con CSS


Quiero que mi imagen de fondo se estire y escale dependiendo del tamaño de la ventana del navegador.

He visto algunas preguntas sobre Stack Overflow que hacen el trabajo, como Estirar y escalar el fondo CSS por ejemplo. Funciona bien, pero quiero colocar la imagen usando background, no con una etiqueta img.

En esa se coloca una etiqueta img, y luego con CSS tribute a la etiqueta img.

width:100%; height:100%;

Funciona, pero esa pregunta es un poco vieja, y afirma que en CSS 3 cambiar el tamaño de una imagen de fondo funcionará bastante bien. He probado este ejemplo el primero, pero no funcionó para mí.

¿Existe un buen método para hacerlo con la declaración background-image?

Author: Community, 2009-07-19

18 answers

CSS3 tiene un pequeño atributo llamado background-size:cover.

Esto escala la imagen para que el área de fondo esté completamente cubierta por la imagen de fondo mientras se mantiene la relación de aspecto. El área entera será cubierta sin embargo parte de la imagen puede no ser visible si el ancho/alto de la imagen redimensionada es demasiado grande

 912
Author: Vashishtha Jogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-15 15:53:16

Podría usar la propiedad CSS3 para hacerlo bastante bien. Cambia el tamaño a la relación, por lo que no distorsiona la imagen (aunque hace imágenes pequeñas de lujo). Solo tenga en cuenta, no está implementado en todos los navegadores todavía.

background-size: 100%;
 451
Author: Matt Burgess,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-28 00:44:54

Usando el código que mencioné...

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

Que produce el efecto deseado: solo el contenido se desplazará, no el fondo.

La imagen de fondo cambia de tamaño a la vista del navegador para cualquier tamaño de pantalla. Cuando el contenido no se ajusta a la vista del navegador y el usuario necesita desplazarse por la página, la imagen de fondo permanece fija en la vista mientras el contenido se desplaza.

Con CSS 3 parece que esto sería mucho sencillo.

 181
Author: Fábio Antunes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:37

CSS:

html,body {
    background: url(images/bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover; /* For WebKit*/
    -moz-background-size: cover;    /* Mozilla*/
    -o-background-size: cover;      /* Opera*/
    background-size: cover;         /* Generic*/
}
 159
Author: CelticParser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-16 00:18:10
background-size: 100% 100%; 

Estira bg para llenar todo el elemento en ambos ejes

 44
Author: yeahdixon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-26 18:34:37

La siguiente parte CSS debe estirar la imagen con todos los navegadores.

Hago esto dinámicamente para cada página. Por lo tanto, utilizo PHP para generar su propia etiqueta HTML para cada página. Todas las imágenes están en la carpeta' image 'y terminan con' Bg.jpg".

<html style="
      background: url(images/'.$pic.'Bg.jpg) no-repeat center center fixed;
      -webkit-background-size: cover;
      -moz-background-size: cover;
      -o-background-size: cover;
      background-size: cover;
      filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\',     sizingMethod=\'scale\');
      -ms-filter: \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/'.$pic.'Bg.jpg\', sizingMethod=\'scale\')\
";>

Si solo tiene una imagen de fondo para todas las páginas, puede eliminar la variable $pic, eliminar las barras oblicuas de escape, ajustar las rutas y colocar este código en su archivo CSS.

html{
    background: url(images/homeBg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg.jpg',     sizingMethod='scale');
    -ms-filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/homeBg', sizingMethod='scale');
}

Esto se probó con Internet Explorer 9, Chrome 21 y Firefox 14.

 39
Author: Thorsten Niehues,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 17:17:51

Utilice este CSS:

background: url('img.png') no-repeat; 
background-size: 100%;
 17
Author: RSH1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-09 09:41:32

Puede lograr el mismo efecto que una imagen de fondo con la etiqueta img. Solo tiene que establecer su índice z más bajo que todo lo demás, establecer posición: absoluta y usar un fondo transparente para cada caja en primer plano.

 16
Author: Kim Stebel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-19 17:14:39

Puede agregar esta clase a su archivo CSS.

.stretch {
            background: url(images/bg.jpg) no-repeat center center fixed;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
}

Funciona en:

  • Safari 3 o posterior
  • Chrome Lo que sea o posterior
  • Internet Explorer 9 o posterior
  • Opera 10 o posterior (Opera 9.5 soportado background-size, pero no las palabras clave)
  • Firefox 3.6 o posterior (Firefox 4 admite versiones sin prefijo de proveedor)
 14
Author: Arunraj S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-14 19:30:19

Explicado por css-tricks https://css-tricks.com/perfect-full-page-background-image /

Demo: https://css-tricks.com/examples/FullPageBackgroundImage/progressive.php

Código:

body { 
  background: url(images/myBackground.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
 12
Author: Aamer Shahzad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-28 06:29:17

Con el fin de escalar sus imágenes adecuadamente en función del tamaño del contenedor es el siguiente:

{
background-size:contain;
background-repeat: no-repeat;
}
 10
Author: justinpees,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-07 18:52:38

Uso esto, y funciona con todos los navegadores:

<html>
    <head>
        <title>Stretched Background Image</title>
        <style type="text/css">
            /* Remove margins from the 'html' and 'body' tags, and ensure the page takes up full screen height. */
            html, body {height:100%; margin:0; padding:0;}

            /* Set the position and dimensions of the background image. */
            #page-background {position:fixed; top:0; left:0; width:100%; height:100%;}

            /* Specify the position and layering for the content that needs to appear in front of the background image. Must have a higher z-index value than the background image. Also add some padding to compensate for removing the margin from the 'html' and 'body' tags. */
            #content {position:relative; z-index:1; padding:10px;}
        </style>
        <!-- The above code doesn't work in Internet Explorer 6. To address this, we use a conditional comment to specify an alternative style sheet for IE 6. -->
        <!--[if IE 6]>
        <style type="text/css">
            html {overflow-y:hidden;}
            body {overflow-y:auto;}
            #page-background {position:absolute; z-index:-1;}
            #content {position:static;padding:10px;}
        </style>
        <![endif]-->
    </head>
    <body>
        <div id="page-background"><img src="http://www.quackit.com/pix/milford_sound/milford_sound.jpg" width="100%" height="100%" alt="Smile"></div>
        <div id="content">
            <h2>Stretch that Background Image!</h2>
            <p>This text appears in front of the background image. This is because we've used CSS to layer the content in front of the background image. The background image will stretch to fit your browser window. You can see the image grow and shrink as you resize your browser.</p>
            <p>Go on, try it - resize your browser!</p>
        </div>
    </body>
</html>
 9
Author: Mahdi jokar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-30 15:55:07

Estoy de acuerdo con la imagen en div absoluto con 100% de ancho y alto. Asegúrese de establecer 100% de ancho y alto para el cuerpo en el CSS y establecer márgenes y relleno a cero. Otro problema que encontrará con este método es que al seleccionar texto, el área de selección a veces puede abarcar la imagen de fondo, lo que tiene el desafortunado efecto de hacer que la página completa tenga el estado seleccionado. Puedes redondear esto usando la regla CSS user-select:none, así:

<html>
    <head>
        <style type="text/css">

            html,body {
                height: 100%;
                width: 100%
                margin: none;
                padding: none;
            }

            #background {
                width: 100%;
                height: 100%;
                position: fixed;
                left: 0px;
                top: 0px;
                z-index: -99999;
                -webkit-user-select: none;
                -khtml-user-select: none;
                -moz-user-select: none;
                -o-user-select: none;
                user-select: none;
            }

            #background img {
                width: 100%;
                height: 100%;
            }

            #main{ z-index:10;}
        </style>
    </head>
    <body>
        <div id="main">
            content here
        </div>
        <div id="background"><img src="bg.jpg"></div>
    </body>
</html>

De nuevo, Internet Explorer es el malo aquí, porque no reconoce la opción de selección de usuario-ni siquiera Internet Explorer 10 preview lo admite, por lo que tiene la opción de usar JavaScript para evitar la selección de imágenes de fondo (por ejemplo, http://www.felgall.com/jstip35.htm ) o usando CSS 3 método de estiramiento de fondo.

También, para SEO Pondría la imagen de fondo en la parte inferior de la página, pero si la imagen de fondo toma demasiado tiempo para cargar (es decir, con un fondo blanco inicialmente), se puede mover a la parte superior de la página.

 8
Author: Myke Black,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-23 15:54:19

Gracias!

Pero entonces no estaba funcionando para el Google Chrome y Safari navegadores (estiramiento funcionó, pero la altura de las imágenes era de solo 2 mm!) , hasta que alguien me dijo lo que falta:

Intenta establecer height:auto;min-height:100%;

Así que cambia eso para tu height:100%; línea, da:

#### #background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    width:100%;
    height:auto;
    min-height:100%;
}

Justo antes de que el código recién añadido tengo esto en mi Drupal Tendu temas style.css:

Html, cuerpo{altura: 100%;}

# page{background: # ffffff; height: auto !importante;height:100%;min-height:100%;position:relative;}

Luego tengo que hacer un nuevo bloque dentro de Drupal con la imagen mientras añado class=stretch:

Simplemente copiar una imagen con el editor en ese bloque de Drupal no funciona; uno tiene que cambiar el editor a texto sin formato.

 7
Author: Cybr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-22 12:09:52

Quería centrar y escalar una imagen de fondo, sin estirarla a toda la página, y quería que se mantuviera la relación de aspecto. Esto funcionó para mí, gracias a las variaciones sugeridas en otras respuestas:

IMAGEN EN LÍNEA: ------------------------

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS ----------------------------------

html {
    height:100%;
}

#background {
    text-align: center;
    width: 100%; 
    height: 100%; 
    position: fixed;
    left: 0px; 
    top: 0px; 
    z-index: -1;
}

.stretch {
    margin: auto;
    height:100%;
}
 6
Author: AnnieDee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-22 12:09:19

Use el complemento Backstretch. Uno podría incluso tener varias imágenes de diapositivas. También funciona dentro de contenedores. De esta manera, por ejemplo, solo se podría haber cubierto una parte del fondo con una imagen de fondo.

Ya que incluso yo podría conseguir que funcione demuestra que es un plugin fácil de usar :).

 4
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-22 12:15:46

Puede utilizar el border-image : yourimage propiedad para escalar la imagen hasta el borde, incluso si le da la imagen de fondo, entonces la imagen del borde se dibujará sobre ella.

La propiedad Border-image es muy útil si su hoja de estilo está implementada en algún lugar que no soporta CSS3 . Si está utilizando chrome de firefox , entonces recomiendo la propiedad background-size:cover en sí.

 1
Author: Natesh bhat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-02 13:51:27

¿Quieres lograr esto solo usando una imagen? Porque en realidad se puede hacer algo similar a un fondo de estiramiento utilizando dos imágenes. PNG imágenes, por ejemplo.

He hecho esto antes, y no es tan difícil. Además, creo que estirar solo dañaría la calidad del fondo. Y si agregas una imagen enorme, ralentizaría computadoras y navegadores lentos.

 -1
Author: MarioRicalde,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-30 15:51:34