Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

Thursday, May 24, 2007

Centering in Safari and IE off by one pixel

If the size of the browser window is an odd number, you'll run into problems with the centering not matching the centering of your html. A friend of mine needed this fixed, as his page elements could not match up with the background. This fix here suggests resizing the browser window to fix the problem. Well, while that is feasible workaround, I'm not sure how usable it is for a user to have their browser modified like this.

And so I cobbled together some javascript for him that basically overrides the background positioning and centers it manually via javascript. Like so:


function positionBackground(){
//set this to the width of your background image
var backgroundImageWidth = 760;

var size = getPageSize();
var body = document.body;
if( navigator.userAgent.indexOf('Safari') != -1 || navigator.appVersion.indexOf("MSIE") != -1)
{
if(size.width % 2 == 1){
size.width -= 1;
}
}

body.style.backgroundPosition = size.width/2 - (backgroundImageWidth / 2);
}

function getPageSize() {
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;
}
return {width:myWidth,height:myHeight};
}

window.onresize = positionBackground;
window.onload = positionBackground;


Unfortunately you're required to input the background image's width by hand, but since this is usually consistent I think its acceptable.

Alas, I'm really unsure that this is a better way of thinking about how to fix things. It really bothers me that the current mentality for rigorous CSS and tableless layouts requires such elaborate javascript fixes to get them to work. But that is a topic for another rant. :)