Background fitting the browser (html/css/javascript)

| 2 min read

This has nothing to do with flash but I share this quick try as I saw a lot of people looking for a background that fit the browser in html.

I used the ratio out I explained in this previous post, obviously you don't have the flash smoothing.

It is not perfect, I had to remove the scrollbars as a part of the picture is not visible. See the demo and download the source.

I'm far from being a good html/css/javascript developer so If you know already a good version or if you have developed one, please let me know.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Soundstep | experiments (html/css background fitting the borwser)</title>
<style>
html, body {
overflow: hidden;
}
</style>
<script type="text/javascript" src="browser.js"></script>
<script>
function fixedBackground(url) {
document.body.style.padding = '0';
document.body.style.margin = '0';
var overlay = document.createElement('DIV');
overlay.style.position = 'absolute';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.height = '100%';
overlay.style.width = '100%';
overlay.innerHTML = document.body.innerHTML;
document.body.innerHTML = '<img id="bg" width="10" height="10" src="' + url + '" style="left: 0; top: 0; z-index: 0" />';
document.body.appendChild(overlay);
backgroundset = true;
updateBackground();
}

function updateBackground() {
var bSize = getSize();
var sWidth = bSize.w;
var sHeight = bSize.h;
var ratio = 1024 / 768;
if (sWidth / ratio < sHeight) sWidth = sHeight * ratio;
else sHeight = sWidth / ratio;
var __bg = document.getElementById('bg');
__bg.top = 0;
__bg.left = 0;
__bg.width = sWidth;
__bg.height = sHeight;
}

function getSize() {
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
}
else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
else if (document.body && ( document.body.clientWidth || document.body.clientHeight )) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
var r = {w:myWidth, h:myHeight};
return r;
}
</script>
</head>

<body onresize="updateBackground()" onload="fixedBackground('bg.jpg')">

</body>
</html>