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

36 comments:

Robert 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?

Rob 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.

Jason Sawtelle 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.

Scott 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...

Takings Our Degraded Prices at www.Pharmashack.com, The Prime [b][url=http://www.pharmashack.com]Online Chemist's snitch on [/url][/b] To [url=http://www.pharmashack.com]Buy Viagra[/url] Online ! You Can also Stick to Embellished Deals When You [url=http://www.pharmashack.com/en/item/cialis.html]Buy Cialis[/url] and When You You [url=http://www.pharmashack.com/en/item/levitra.html]Buy Levitra[/url] Online. We Also Classify a Abundant Generic [url=http://www.pharmashack.com/en/item/phentermine.html]Phentermine[/url] Recompense the improve of Your Victuals ! We Detail away Deal signpost [url=http://www.pharmashack.com/en/item/viagra.html]Viagra[/url] and Also [url=http://www.pharmashack.com/en/item/generic_viagra.html]Generic Viagra[/url] !

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

I'm new around here, seems like a cool place though. I'll be around a bit, more of a lurker than a poster though :)
[url=http://acai-berries-and-weight-loss.wetpaint.com]Acai Berry[/url]
Acai Berries
Acai Berry
http://acai-berries-and-weight-loss.wetpaint.com
Acai Berry

Anonymous said...

[b]Website Traffic[/b]

A new way to get traffic to your website. Not only will you get loads of [url=http://www.fastpixeltraffic.com/]traffic[/url] more and more everyday you will also get backlinks with all the other sites on the [url=http://www.fastpixeltraffic.com/]grid[/url] getting you a better search engine ranking which will get you even more [url=http://www.fastpixeltraffic.com/]website traffic[/url].Get on the pixel grid today and let the traffic come to you.Taking the internet by storm.The new way to advertise.

Visit: http://www.fastpixeltraffic.com/

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

Generic Viagra is the world renowned medicine for erectile dysfunction and most men have forgotten they ever had a problem with erections after its use. Take it on empty stomach and it will work in 30 minutes. Erections can be achieved on stimulation.Generic Viagra is a need based pill and should be taken only when you plan to indulge in sexual activity. Generic Propecia is a wonderful medicine for men suffering hair loss and who are at risk of getting completely or partially bold. Propecia can also help you at the beginning stages of some prostatic problems. Viagra improves erections for most men no matter how long they have had erectile dysfunction, taken approximately 30 minutes before your plan of sexual activity and works on stimulation for around 4 hours.Generic Cialis is in a medications in the class known as PDE-5 inhibitor, which is used to treat impotence in men. Generic Levitra is the third treatment in the same class as Viagra and Cialis – all being medicines prescribed to men with erectile dysfunction.

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 ?

Poker said...

This is extremely impressive content. I like how you brought forward many clear viewpoints and I agree with many. Your article coaxes thought out of the reader from start to finish. I really like this.
--------------------------
Bonus Sans Depot & Bonos Sin Deposito Poker & Bonus ohne einzahlung & Poker Bonus senza deposito

Poker said...

Your blog post is very unique and well research, Thanks for your research on academic knowledge…
--------------------------
My site: Poker Without Deposit 100% free poker !

Poker said...

Only an open-minded person could write this kind of content. I agree with your points and I really enjoyed this article a lot. Great article!
--------------------------
Website: Poker Sign up Bonuses

Poker said...

This is really very informative site and all your articles are hot as hell, lots of useful stuff. One thing I just want to say is that your Blog is so perfect to me.
--------------------------
Our website: Texas Holdem Poker

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


Xanax[url=http://www.xanax.vg]Xanax[/url]http://www.xanax.vg
Online Adderall[url=http://www.adderall-online.us] Online Adderall[/url]http://www.adderall-online.us
Viagra [url=http://www.viagradeals.us]Viagra [/url]http://www.viagradeals.us
Levitra[url=http://www.levitrarxusa.com]Levitra[/url]http://www.levitrarxusa.com

Anonymous said...


Cialis[url=http://www.cialis.ms]Cialis[/url]http://www.cialis.ms
Viagra Online Without Prescription[url=http://www.viagra-online-without-prescription.org]Viagra Online Without Prescription[/url]http://www.viagra-online-without-prescription.org
Ativan[url=http://www.ativan.name]Ativan[/url]http://www.ativan.name

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

Anonymous said...


https://www.mac.cs.csi.cuny.edu/groups/csc126/wiki/90ed0/Advantages_of_The_Blue_Pill.html

viagra, [url=https://online.hiram.edu/mahara/view/view.php?id=1466]viagra[/url],

https://online.hiram.edu/mahara/view/view.php?id=1466

viagra, [url=http://moodle.delmar.edu/mahara/view/view.php?id=877]viagra[/url],

http://moodle.delmar.edu/mahara/view/view.php?id=877

viagra, [url=https://vbwiki.medicine.tamhsc.edu/groups/homework2/wiki/86655/Advantages_of_The_Blue_Pill.html]viagra[/url],

https://vbwiki.medicine.tamhsc.edu/groups/homework2/wiki/86655/Advantages_of_The_Blue_Pill.html

viagra, [url=http://mahara.chatham.edu/view/view.php?id=1687]viagra[/url],

http://mahara.chatham.edu/view/view.php?id=1687

viagra, [url=http://moodle.obu.edu/mahara/view/view.php?id=1092]viagra[/url],