Background image full screen css

New Page

Cómo – Full Page Image

❮ Próximo previous ❯

Learn how to create a full page background image with CSS.

Full Page Image

Aprenda a crear una imagen de fondo que cubra toda la ventana del navegador. El siguiente ejemplo muestra una imagen de fondo receptiva de pantalla completa (y media pantalla):

Demo: Full Page Background Image

Demonstration: background image from media page

How to create an image of altura completea

Use an element containing or aggregate a background image with content or with height: 100%. Suggestions: use 50% to create a background image from the media page. Luego uses the following propiedades de fondo para centrar y escalar la imagen perfectly:

Nota: Para asegurarse de que la imagen cubra toda la pantalla, también debe aplicar height: 100%tanto a <html> como a <body>:

Example

body, html { height: 100%;} .bg { /* The image used */ background-image: url(“img_girl.jpg”); /* Full height */ height: 100%; /* Center and resize the image nicely */ background-position: center; background repeat: no repeat; background size: cover ;}

Inténtalo tú mismo”

Media page background image:

Example

.bg { height: 50%; }

Inténtalo tú mismo”

❮ Próximo previous ❯

May 2, 2020 / #CSS

CSS background image tamaño tutorial: how to codify a complete page background image

Joe LiangJoe LiangCSS background image tamaño tutorial: how to codify a complete page background image

This tutorial shows a sencilla form of coding a complete page background image using CSS. Y también aprenderá cómo hacer que esa imagen responda al tamaño de pantalla de sus usuarios.

Hacer que un imagen de fondo se extienda por completeo para cubrir toda la ventana del navegador est una tarea común en el diseño web. Unfortunately, this tarea can be realized with some lines of CSS.

Cubrir ventana gráfica con imagen

Primero, querremos asegurarnos de que nuestra página realmente cubra toda la ventana gráfica:

html { min-height: 100%; }

Dentro html, usaremos the background-image propiedad para establecer la imagen:

background image: url(image.jpg); /*replace image.jpg with the path to your image*/ Magic of the ‘Tamaño de fondo’ property

The magic succeeds with the background size property:

bottom size: blanket;

cover tells the browser to ensure that the image always covers the entire container, in this case html. The browser will cover the container even if it needs to stretch the image or trim the edges a bit.

Since the browser can stretch the image, you should use a high enough resolution background image. Otherwise, the image may appear pixelated.

If you care about having the whole image appear in the background, you’ll want to make sure the image is relatively close in aspect ratio to screen size.

How to refine the position of an image and avoid tiling

The browser can also choose to display your background image as tiles depending on its size. To prevent this from happening, use no-repeat:

background repeat: no repeat;

To keep things pretty, we’ll keep our image always centered:

background position: center center;

This will center the image both horizontally and vertically at all times.

We have now produced a fully responsive image that will still cover the entire background:

html { min-height: 100%; background image: url(image.jpg); bottom size: blanket; background repeat: no repeat; background position: center center; } How to fix an image in place when scrolling

Now, just in case you want to add some text above the background image and that text overflows the current window, you might want to make sure your image stays in the background when the user scrolls down to see the rest of the text:

background attachment: fixed;

You can include all of the background properties described above using short notation:

background: url (image.jpg) center center cover without fixed repeat; Optional: How to add a media query for mobile

To add some icing on the cake, you can add a media query for small screens:

@media only screen and (max-width: 767px) { html { background-image: url(smaller-image.jpg); } }

Vous pouvez utiliser Photoshop ou un autre logiciel de retouche d’image pour réduire la taille de votre image d’origine afin d’améliorer la vitesse de chargement des pages sur les connexions Internet mobiles.

Alors maintenant que vous connaissez la magie de la création d’un arrière-plan d’image pleine page réactif, il est temps d’aller créer de beaux sites Web !

Vous voulez voir plus de conseils et de connaissances sur le développement Web ?

  • Abonnez-vous à ma newsletter hebdomadaire
  • Visitez mon blog à 1000 Mile World
  • Suis moi sur Twitter

PUBLICITÉ

PUBLICITÉ

PUBLICITÉ

Joe LiangJoe Liang

Développeur web indépendant

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTISEMENT

background

Perfect Full Page Background Image

Avatar of Chris Coyier

Chris Coyier on Nov 20, 2010 (Updated on Sep 30, 2022)

Let’s put those CSS skills to work! Claim $50 in free hosting credit on Cloudways with code CSSTRICKS.

This post was originally published on August 21, 2009 and is now updated as it has been entirely revised. Both original methods are removed and now replaced by four new methods.

The goal here is a background image on a website that covers the entire browser window at all times. Let’s put some specifics on it:

  • Fills entire page with image, no white space
  • Scales image as needed
  • Retains image proportions (aspect ratio)
  • L’image est centrée sur la page
  • Ne provoque pas de barres de défilement
  • Aussi compatible avec tous les navigateurs que possible
  • N’y a-t-il pas des manigances fantaisistes comme Flash

full page background

Méthode CSS géniale, facile et progressive

We can do this only through CSS thanks to the background-size property now in CSS. We’ll use the html element (better than body because it’s always at least the height of the browser window). We set a fixed, centered background on top of it, then adjust its size using background-size set to the cover keyword.

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

Work in:

  • Safari 3+
  • Chrome whatever+
  • Internet Explorer 9+
  • Opera 10+ (Opera 9.5 supports background size but not keywords)
  • Firefox 3.6+ (Firefox 4 supports non-vendor prefixed version)

See the demo

Update: Thanks to Goltzman in the comments for pointing out an article from Adobe Developer Connection that has code that allows IE to cover backgrounds as well:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’.myBackground.jpg’, sizingMethod=’scale’); -ms-filter: “progid:DXImageTransform.Microsoft.AlphaImageLoader(src=’myBackground.jpg’, sizingMethod=’scale’)”;

But beware, reader Pierre Orsander said they tried this and had some issues with links on the page dying.

Update: Matt Litherland writes in to say that anyone trying to use the above IE filters and having problems with scrollbars or dead links or whatever else (like Pierre above) should try not using them on the html or body element. But instead a fixed position div with 100% width and height.

CSS-only technique #1

Big thanks, as usual, to Doug Neiner for this alternate version. Here, we use an inline element, which will be able to resize in any browser. We set a min-height which keeps it filling the browser window vertically, and set a 100% width which keeps it filling horizontally. We also set a min-width of the width of the image so that the image never gets smaller than it actually is.

The particularly clever part is to use a media query to check if the browser window is smaller than the image, and use a combined percentage of left and negative left margin to keep it centered regardless.

Here is the CSS:

img.bg { /* Set rules to fill background */ min-height: 100%; min width: 1024px; /* Configure proportional scaling */ width: 100%; height: automatic; /* Configure positioning */ position: fixed; high: 0; left: 0; } @media screen and (max-width: 1024px) { /* Specific to this particular image */ img.bg { left: 50%; left margin: -512px; /* 50% */ } }

Work in:

  • All versions of good browsers: Safari / Chrome / Opera / Firefox
  • IE 6: Borked – but probably fixable if you use some kind of fixed positioning wedge
  • IE 7/8: Works mostly, doesn’t focus on small sizes but fills the screen well
  • Internet Explorer 9: Works

See the demo

CSS technique only #2

A fairly easy way to handle this is to place an inline image on the page, position it top left, and give it a minimum width and height of 100%, preserving its aspect ratio.

<img class=”bg” src=”images/bg.jpg” alt=””> .bg { position: fixed; high: 0; left: 0; /* Keep aspect ratio */ min-width: 100%; min height: 100%; }

However, that doesn’t center the image and that’s a pretty common wish here… So we can solve that by wrapping the image in a div. This div will be twice as large as the browser window. Then the image will be placed, always preserving its aspect ratio and covering the visible browser window, and the dead center of it.

<div class=”bg”> <img src=”images/bg.jpg” alt=””> </div> .bg { position: fixed; high: -50%; left: -50%; width: 200%; height: 200%; } .bg img { position: absolute; high: 0; left: 0; right: 0; low: 0; margin: automatic; min-width: 50%; min height: 50%; }

Thanks to Corey Worrell for the concept of this one.

Work in:

  • Safari / Chrome / Firefox (hasn’t been tested very far, but recent versions are fine)
  • Internet Explorer 8+
  • Opera (any version) and IE both fail the same way (poorly positioned, not sure why)
  • Peter VanWylen wrote to say that if you add the image via JavaScript, the img must have width: auto; and height: automatic; to work in IE 8, 9 or 10.

See the demo

January 2018 Update: Try making this work on Android? JL García wrote to me that he needed to add height: 100%; and overflow: hidden; to the html element to make it work. The full extract being:

html { background: url(images/bg.jpg) no-repeat center center fixed; bottom size: blanket; height: 100%; hidden overflow; }

I tested it, and it seemed fine to me. Without her / With her.

jQuery method

This whole idea becomes much easier (from a CSS point of view) if we know if the aspect ratio of the image (inline that we intend to use as a background) is bigger or smaller than the current aspect ratio of the browser window. If it is less, we can only set the width to 100% on the image and know that it will fill both height and width. If it is higher, we can set only the height to 100% and know that it will fill both height and width.

We access this information via JavaScript. As usual here, I like to rely on jQuery.

<img id=”bg” src=”images/bg.jpg” alt=””> #bg { position: fixed; high: 0; left: 0; } .bgwidth { width: 100%; } .bgheight { height: 100%; } $(window).load(function() { var theWindow = $(window), $bg = $(“#bg”), aspectRatio = $bg.width() / $bg.height(); function resizeBg( ) { if ( (theWindow.width() / theWindow.height()) < aspectRatio ) { $bg .removeClass() .addClass(‘bgheight’); } else { $bg .removeClass() .addClass(‘bgwidth’ ); } } theWindow.resize(resizeBg).trigger(“resize”); });

This doesn’t account for centering, but you can certainly modify this to do so. Credits to Koen Haarbosch for the concept behind this idea.

Work in:

  • IE7 + (probably could go into IE6 with a fixed posición cuña)
  • The mayoría of cualquier otro navegador de escritorio

Ver demonstration

Actualización (junio de 2012): el lector Craig Manley escribe con una técnica para cargar une imagen de fondo del tamaño adecuado según la pantalla. Like this, no frills a large ancho 1900px background image for an iPhone.

Primero, create images as 1024.jpg, 1280.jpg, 1366.jpg, etc. Luego, en lugar de cargar una imagen, cargaría una corrección.

<img id=”bg” style=”position: fixed; left: 0; top: 0;” src=”data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAAIBRAA7″ alt=””>

Si no te gusta el gif shim (personally, creo que está bien porque no es “contenido”, es un fondo), puedes cargar una de las imágenes reales en su lugar. Este code dará cuenta de eso.

Luego, prueba el ancho de la pantalla y establece el srcde la imagen en función de él. El siguiente código lo hace al cambiar el tamaño, lo que puede o no desear. Podrías ejecutar el código una vez si quisieras.

log(‘Chosen background: ‘ + chosen); } // Determine whether width or height should be 100% if ((win_w / win_h) < ($bg.width() / $bg.height())) { $bg.css({height: ‘100 %’, width: ‘self’}); } else { $bg.css({width: ‘100%’, height: ‘auto’}); } }).resize(); })(jQuery)</available.length;>

Tenga en cuenta que el ancho de la pantalla no es la única buena información que se puede tener al elegir un tamaño de imagen. Vea este articulo.

Disfruitar

If usa esto, no dude en dejar qué técnica usó y si la modificó de alguna manera en los comentarios a continuation. Siempre es genial ver técnicas “en la naturaleza”.

Download archive

Solo por el bien de la posteridad, hay otro ejemplo aquí llamado table.phpque usa una técnica antigua que solía ser parte de este artículo. Tenía cierta cleverness, pero no era tan buena como ninguna de las técnicas CSS presentadas anteriormente.

Other Resources

  • Vegas jQuery add-on (Jay Salvat)
  • How to change the opacity of a background image (DigitalOcean)


Video Background image full screen css

Related Posts

Free chat room code for my website

Contents1 How to set up a free chat room on the website.2 3 comentarios2.1 Trackbacks/Pingbacks2.2 Submit a Comment Cancel reply3 How to Create a Chat Room Website…

WordPress leverage browser caching

Contents1 Aproveche el almacenamiento in hidden del navegador1.1 Will it works for my website?1.2 Where are plugin options1.3 Some JavaScript files still display under Leverage Browser Caching1.4…

WordPress post to facebook page

Contents1 How to Automatically Post to Facebook from WordPress1.1 Download Now: How to Launch a WordPress Website [Free Guide + Checklist]1.2 1. Create an IFTTT account.1.3 2….

Download images from wordpress media library

Contents1 How to export your WordPress media library1.1 Download maintenant : How to launch a WordPress website [Free Guide + Checklist]1.2 How to export your WordPress media…

WordPress single post template

Contents1 How to Create Custom Unique Post Templates in WordPress2 Post Template Files2.1 author.php2.2 Fecha.php3 Handbook navigation4 How to Create Custom Single Post Templates in WordPress5 Video…

Remove page title in wordpress

Contents1 How to hide titles of pages and publications in WordPress1.1 ¿Apurado? Save this article as a PDF.1.2 Contents1.3 SEO Considerations1.4 What’s the Difference Between Title Tag…