Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image centered and 100% in all browsers

What is the best practice to set a background image centered and 100% (so that it fills the screen, but still retains the aspect ratio) in all browsers?

like image 838
jamietelin Avatar asked May 10 '10 14:05

jamietelin


People also ask

How do I keep the background of a picture in the center?

You need to specify the position of the image through the "center" value of the background shorthand property. Set the width of your image to "100%". In this example, we also specify the height and background-size of our image.

How do I make the background image fit all screen size in HTML?

Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.

How do I make an image fit my website background?

When you work with background images, you may want an image to stretch to fit the page despite the wide range of devices and screen sizes. The best way to stretch an image to fit the background of an element is to use the CSS3 property, for background-size, and set it equal to cover.


2 Answers

Best solution I have managed to make so far is as follows;

//CSS
<style type="text/css">
   body {
       margin:0; padding:0;
   }
   html, body, #bg {
       height:100%;
       width:100%;
   }
   #bg {
       position:absolute; 
       left:0;
       right:0;
       bottom:0;
       top:0;
       overflow:hidden;
       z-index:0;
   }
   #bg img {
       width:100%;
       min-width:100%;
       min-height:100%;
   }
   #content {
       z-index:1;
   }
</style>

//HTML
<body>
<div id="bg">
   <img style="display:block;" src="bgimage.jpg">
</div>
<div id="content">
   //Rest of content
</div>
</body>

Might this be best way? Anyone see any problems with doing it this way?

Thanks for your time!

like image 141
jamietelin Avatar answered Oct 04 '22 09:10

jamietelin


The best practice is to not to do what you want to do.

By specifying 100% you are going to stretch (thus distort) the image.

The best way to have a simple, centered background is like this:

body {
    background-image:url(Images/MyBG.png);
    background-position:center top;
    background-repeat:no-repeat
}

EDIT:

Now you CAN target different resolutions and use a different background image, depending on the size by specifying a resolution-dependent stylesheet. You can use separate stylesheets just to define the one background element with different files in each.

<link rel="stylesheet" media="screen and (min-device-width: 800px)" href="800.css" />

See: http://css-tricks.com/resolution-specific-stylesheets/

or the W3C CSS media query spec.

like image 44
Diodeus - James MacFarlane Avatar answered Oct 04 '22 08:10

Diodeus - James MacFarlane