View Demo | View Code
To view the concept in a real world scenario take a look at http://www.thenorthface.com.
The HTML:
<body> <img id="bgImg" alt="" src="bckgrnd.jpg"/> <div id="realScroller"> <div id="contentDiv"> The background of this page will remain the full width or height of the browser window, whichever is larger. </div> </div> </body>
To keep it simple I place an IMG tag just inside the BODY of the page. Next is a DIV with an ID of “realScroller” that will be the element that handles the scrolling. Next is a div that is the container of the site’s content.
The CSS:
html,body {height:100%; margin:0; overflow:hidden;} #bgImg {left:0; position:absolute; top:0; z-index:-1;} #realScroller {height:100%; overflow:auto;} #contentDiv {border:3px double black; color:orange; font-family:Georgia,serif; font-size:5em; margin:5% auto 0; overflow:hidden; padding:1%; text-align:justify; width:75%;}
In the CSS the HTML and BODY tags are given a height of 100% so they are always the full size of the browser. Also their OVERFLOW property is set to HIDDEN so that their scrollbars never appear. Most browsers put an eight pixel MARGIN around the BODY tag so that is reset to ZERO.
The background IMG element is given a POSITION of ABSOLUTE. Which takes it out of the normal flow of the document and it acts as a layer. The z-index is set to NEGATIVE ONE so that it sits behind the content of the page. I prefer doing this instead of lifting the content container up to a higher z-index.
The jQuery:
$(window).bind('load resize', function(){ var $winHeight = $(window).height(), $winWidth = $(window).width(), $bgImg = $('#bgImg'); if ($winHeight > $winWidth){ $bgImg.css({'height':'100%','width':'auto'}); } else{ $bgImg.css({'height':'auto','width':'100%'}); } });
The first line binds a function to the load and resize events of the window. Every time the window is resized jQuery gets the height and width. If the height is greater than the width then the background image height is set to 100%. The width is set to auto so that the aspect ratio of the image is not distorted. The reverse happens if the window width is greater than the height.
NOTE: A key to this working well is to use a background image that is square. If the background image is not square there will be a *jump* when it changes from being full width to full height or the reverse. If your image is not square, edit it. You might need to add a fade into the background color.