- Fills entire page with image, no white space
- Scales image as needed
- Retains image proportions
- Image is centered on page
- Does not cause scrollbars
- Cross-browser compatible
- Isn’t some fancy shenanigans like Flash
Technique #1
This inline image is going to be placed on the page inside of a bunch of wrappers, each necessary for accomplishing all our goals.<div id="bg">
<div>
<table cellspacing="0" cellpadding="0">
<tr>
<td>
<img src="images/bg.jpg" alt=""/>
</td>
</tr>
</table>
</div>
</div>
And the CSS:
* {
margin: 0;
padding: 0;
}
html, body, #bg, #bg table, #bg td {
height:100%;
width:100%;
overflow:hidden;
}
#bg {
position: fixed;
}
#bg div {
height:200%;
left:-50%;
position:absolute;
top:-50%;
width:200%;
}
#bg td {
text-align:center;
vertical-align:middle;
}
#bg img {
margin:0 auto;
min-height:50%;
min-width:50%;
}
That’s quite a little load of markup and CSS, but it does the trick very well! Just doing this alone gets the job done, but what about if we want actual content on the page. Setting that overflow to hidden on the html and body elements should scare you a little bit, as that will totally cut off any content that is below the fold on a site with no scrollbars. In order to bring back scrollable content, we’ll introduce another wrapper. This one will sit on top of the background, be the full width and height of the browser window, and set the overflow back to auto (scrollbars). Then inside of this wrapper we can put content safely.
<div id="cont"> <div> <!-- content in here --> </div> </div>
#cont { position:absolute; top:0;left:0; z-index:70; overflow:auto; } .box { margin: 0 auto; width: 400px; padding: 50px; background: white; padding-bottom:100px; font: 14px/2.2 Georgia, Serif; }
JavaScript Fixes
For IE 6, there is some MooTools stuff going on to fix it up In Firefox, default “focus” is placed on the body element when the page loads. That means that pressing the space bar will scroll down the body, which would reveal some ugly white space. We can use some jQuery for a quick fix, to remove that focus and place it on a hidden element instead, removing that problem:$(function(){
$(".box").prepend('<input type="text" id="focus-stealer" type="hidden" />');
$("#focus-stealer").focus();
});
The addition of fixed positioning on the #bg wrapper eliminated the space bar/scrolldown problem. CSS FTW!
View Demo Download FilesRevisions
- September 2, 2015 @ 14:26:46 [Current Revision] by PeterLugg
- September 2, 2015 @ 14:26:46 by PeterLugg
Revision Differences
There are no differences between the September 2, 2015 @ 14:26:46 revision and the current revision. (Maybe only post meta information was changed.)
No comments yet.