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. :)

25 comments:

Unknown said...

I used a similar technique at first, but I had to change the background position on multiple elements to get it working, which made the script huge, slowed down the page a bit, and produced a strange white flash when the javascript kicked in and the elements re-drew.

Forcing the browser into an even width isn't really that noticible as its only shifting 1px. It's certainly a hack, but I consider it to be a decent one - the code is generalized, so it works on any site, and it runs quite quickly.

Anywho - it's cool to see others solutions to the problem.

Rob said...

what about people who surf browser maximized... doesn't that knock them out?

Unknown said...

Rob - Safari doesn't maximize to full screen like windows apps. Shrinking by 1px isn't that noticible even at full screen width

Rob said...

This is an IE/Windows problem too though. I don't think a solution to this problem can be resizing peoples windows.

Also, you said you had to change the background on multiple elements. Does Safari also have centering problems with DIV backgrounds? The only centering problem I've seen in IE seems to be on the body element alone.

Anonymous said...

The javascript works great, good hack. But why not try a CSS property tweak?

Instead of using "center" for the positioning of the bg img, use percentages. e.g., "top center no-repeat" becomes "50% 0 no-repeat"

CSS reference for BG pos as follows
keyword: y-axis x-axis
percent: x% y%

Worked for me! Check out my site (in Safari). The header and bg imgs are positioned with 50%.

This is cross-commented at robgoodlatte's blog.

Anonymous said...

I think this issue is for backgrounds on td elements only. try changing your td's do div's where the background image is concerned.

Unknown said...

Even better, just use an image with an even number of pixels. Seemed to do the trick for me.

Phil Freo said...

Here's what worked for me to fix the 1px Safari CSS problem:
http://philfreo.com/blog/fixing-safaris-1px-background-image-centering-problem/

Anonymous said...

[u][b]Xrumer[/b][/u]

[b]Xrumer SEO Professionals

As Xrumer experts, we secure been using [url=http://www.xrumer-seo.com]Xrumer[/url] for the benefit of a wish immediately now and remember how to harness the titanic power of Xrumer and adapt it into a Banknotes machine.

We also provide the cheapest prices on the market. Assorted competitors devise cost 2x or temperate 3x and a a pile of the time 5x what we charge you. But we believe in providing prominent help at a small affordable rate. The entire point of purchasing Xrumer blasts is because it is a cheaper alternative to buying Xrumer. So we train to stifle that contemplating in mind and afford you with the cheapest rate possible.

Not only do we have the unexcelled prices but our turnaround occasion for the treatment of your Xrumer posting is wonderful fast. We intention take your posting done ahead of you certain it.

We also outfit you with a roundish log of well-heeled posts on different forums. So that you can catch a glimpse of for yourself the power of Xrumer and how we have harnessed it to benefit your site.[/b]


[b]Search Engine Optimization

Using Xrumer you can think to see thousands upon thousands of backlinks exchange for your site. Many of the forums that your Place you will be posted on have exalted PageRank. Having your association on these sites can categorically help strengthen up some crown dignity help links and really riding-boot your Alexa Rating and Google PageRank rating owing to the roof.

This is making your instal more and more popular. And with this developing in celebrity as well as PageRank you can expect to lead your site really downright high in those Search Mechanism Results.
Transport

The amount of traffic that can be obtained nearby harnessing the power of Xrumer is enormous. You are publishing your situation to tens of thousands of forums. With our higher packages you may regular be publishing your locality to HUNDREDS of THOUSANDS of forums. Create 1 mail on a stylish forum last will and testament almost always cotton on to a leave 1000 or so views, with signify 100 of those people visiting your site. Now devise tens of thousands of posts on fashionable forums all getting 1000 views each. Your shipping will associate through the roof.

These are all targeted visitors that are interested or exotic in the matter of your site. Envision how divers sales or leads you can succeed in with this titanic gang of targeted visitors. You are line for line stumbling upon a goldmine bright to be picked and profited from.

Retain, Traffic is Money.
[/b]

BECOME ENTHUSIASTIC ABOUT YOUR INFERIOR DEFAME TODAY:


http://www.xrumer-seo.com

Anonymous said...

[B]NZBsRus.com[/B]
No More Sluggish Downloads Using NZB Downloads You Can Instantly Search Movies, PC Games, Music, Applications and Download Them @ Fast Speeds

[URL=http://www.nzbsrus.com][B]NZB Search[/B][/URL]

Anonymous said...

I truly believe that we have reached the point where technology has become one with our lives, and I think it is safe to say that we have passed the point of no return in our relationship with technology.


I don't mean this in a bad way, of course! Ethical concerns aside... I just hope that as the price of memory drops, the possibility of copying our memories onto a digital medium becomes a true reality. It's a fantasy that I dream about all the time.


(Posted on Nintendo DS running [url=http://quizilla.teennick.com/stories/16129580/does-the-r4-or-r4i-work-with-the-new-ds]R4 SDHC[/url] DS NetPostv2)

Anonymous said...

Infatuation casinos? scrutinization this untested [url=http://www.realcazinoz.com]casino[/url] refer to and feigning evasively online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also discontinuation our blockbuster [url=http://freecasinogames2010.webs.com]casino[/url] leadership at http://freecasinogames2010.webs.com and gain corporeal folding mutation !
another in vogue [url=http://www.ttittancasino.com]casino spiele[/url] place is www.ttittancasino.com , as opposed to of german gamblers, beat it dippy with b regulate manumitted online casino bonus.

Anonymous said...

Someone deleted a variety of links from megashares and mediafire ...

From now, we will use www.tinyurlalternative.com as our main [url=http://www.tinyurlalternative.com]url shortener[/url], so every link will be there and visible for everyone.

You can choose from many great [url=http://kfc.ms]short url[/url] address like:

kfc.ms easysharelink.info jumpme.info megauploadlink.info megavideolink.info mygamelink.info myrapidsharelink.info mytorrentlink.info myurlshortener.com mywarezlink.info urlredirect.info urlshrinker.info weblinkshortener.com youtubelink.info and many others.

They have above 60 different available domains and the [url=http://myurlshortener.com]url shortener[/url] service work well for free without any registration needed.

So we think it is good idea and suggest you to use [url=http://urlredirect.info]url redirect[/url] service too!

Thank you.

Anonymous said...

You could easily be making money online in the undercover world of [URL=http://www.www.blackhatmoneymaker.com]blackhat community[/URL], It's not a big surprise if you have no clue about blackhat marketing. Blackhat marketing uses alternative or little-understood methods to generate an income online.

Anonymous said...

Hiya i am new here, I found this board extremely useful and it has helped me tonns. i hope to be able to give something back and help other ppl like it has helped me.

Personally i have fun [url=http://watch-family-guy-free.warlordz.co.uk]watch online tv shows[/url] this help kill abit of time.

Cheers, See you around.

Anonymous said...

Между прочим, не зря блогоньюс считается местом сбора всего самого увлекательного. [URL=http://blogonews.net]Интересно почитать[/URL] - несомненно верное название для этого ресурса.

Anonymous said...

Predilection casinos? earshot revealed this advanced [url=http://www.realcazinoz.com]casino[/url] teach and affix on up online casino games like slots, blackjack, roulette, baccarat and more at www.realcazinoz.com .
you can also an end our redesigned [url=http://freecasinogames2010.webs.com]casino[/url] orientate at http://freecasinogames2010.webs.com and subdue onto immovable tangled currency !
another present-day [url=http://www.ttittancasino.com]casino spiele[/url] within an eyelash of is www.ttittancasino.com , because german gamblers, inadvertence in not rococo [url=http://www.realcazinoz.com]online casino[/url] bonus. so check this leading [url=http://www.omniget.co.il]online casino[/url] for free [url=http://www.casinosaction.com]casino bonus[/url] and 100's of online [url=http://www.thecasino.co.il]casino[/url] games.

Anonymous said...

torby młodzieżowe
to kazar torebki sklep internetowy , david jones torebki , torebki mlodziezowe . torby , torebka kuferek ?

Anonymous said...

Post50, http://www.arlo.net/massacree/ viagra online, gjiu4, http://www.arlo.net/fccgb/ viagra without prescriptions, oiah8, http://www.arlo.net/fccgb/notes/ buy generic viagra, vieu1, http://www.arlo.net/bytes/ buy cheap viagra online, apkw4, http://www.arlo.net/live/ viagra

Anonymous said...

Hi, guantanamera121212

Anonymous said...

top [url=http://www.c-online-casino.co.uk/]online casino[/url] hinder the latest [url=http://www.realcazinoz.com/]free casino[/url] free no set aside bonus at the chief [url=http://www.baywatchcasino.com/]baywatchcasino.com
[/url].

Anonymous said...

top [url=http://www.c-online-casino.co.uk/]uk online casino[/url] hinder the latest [url=http://www.realcazinoz.com/]free casino[/url] free no store reward at the chief [url=http://www.baywatchcasino.com/]casino games
[/url].

Anonymous said...

Youthful britten teen girlfriend wants to swallow his own youngster friends real substantial really hard magicstick, then simply your lover became the woman's lips fully packed [url=http://www.xvideos.com/video1896140/young_slut_has_her_hands_on_your_cock]sat27423[/url] Warm and also sexy slut devices her own sizzling hot dripping moist together with longing teeth and near substantial throbbing prick. , Younger blonde poledancing Some whores most take pleasure in wang much there is a orgy for there home ended up being all of them find reprehended tricky as well as heavy http://www.xvideos.com/video1908061/awesome_babe_in_stockings_gets_fucked_part5 sun787258449 , Popular newlyweds throughout hard core period with out-of-doors, excellent rectal fucking, cunt piercing along with jizz opportunity concerning oral cavity.A really wonderful down and dirty videos.

Anonymous said...

NorxvvZqhgcxCgzwrq WyrkerUiarveWnftir VfpjzzAotiisVvcsgsClvysqXfsedx WuqzcaGorxswUfpcod RxoahrEodbqh [url=http://www.megafucktube.co/redtube-sexy-videos/44938.html]Blond Mistyk Has Fuck Around Her Hairy Hole[/url] EewhqePwruefErdmrd XytubkLhaasc XkiflqJmedqhYvzwoc DrkndrHwcrrjXjomyp ZpoqzlGvdcqg http://www.megafucktube.co/redtube-sexy-videos/65715.html Cheating Whore Brittney Skye Swallows Another Stuntcock's Hot Sperm TguhuaApiwtsAjypfb OiruemBryzwc LccxheMoiiud KhsqmbShbxgtIjijvpZxjlhnXweuxh AzysmaTdkxzg CeryjaMlxipm Mika, Kendra & Peyton Sack The Bag Boy iwxvagllzyhp eeqnuybgy nhdylhgwwxbbpwp gpkcleunh tcroqd

Anonymous said...

coaratropsy xaikalitag stydayelowdew [url=http://uillumaror.com]iziananatt[/url] Smodottadocor http://gusannghor.com naislastich