JUL
02
How to fix 1px background centering error in Firefox using jQuery

Short version If you already have jQuery included, fixing 1px background centering error in Firefox is easy – just detect Firefox and change background’s horizontal position to 49.99% while leaving 50% in all other browsers

Although i’ts nice to blame every coding problem on IE, Firefox has its share of bugs too. One of those is 1px background centering offset. It goes like this: when you try to match centered body background with the background of your centered div, you get 1px offset whenever the browser window pixel width is odd. For even width, background centers ok.

There is no way around it in css (some tutorials say that you just need to add 100% height to the body, but that doesn’t work) but there is a simple solution using jQuery (or any other library which lets you change the css property of an element). Agreed, including jQuery just to fix this is an overkill, but chances are, you already use it for something else in your page.

First thing, we need to detect Firefox. Latest jQuery version doesn’t have browser detection function, instead they put a function which tells you what the browser support and what not. We’re not going to use that. There is a nice line of code for browser detection, which worked great for me in the past, and I have no idea where I found it, but here goes:

B = (function x(){})[-5]=='x'?'FF3':
        (function x(){})[-6]=='x'?'FF2':
            /a/[-1]=='a'?'FF':
                '\v'=='v'?'IE':
                    /a/.__proto__=='//'?'Safari':
                        /s/.test(/a/.toString)?'Chrome':
                            /^function \(/.test([].sort)?'Opera':
                                'Unknown'

It just works. And then you just need to give special css rule, just for Firefox –

if(B == 'FF') { $('body').css('background-position','49.99% 0'); }

Ta-daaa! All browsers are happily centering with 50% and Firefox is forced to always center the background to the left, which makes it perfectly matching your centered div.

What do you think about this?