Phil Freo Web Development

Fixing Safari’s 1px background-image centering bug

I’m working on slicing and CSS for a new theming project for Magento Commerce and was plagued with a CSS bug that affects WebKit (Safari and Google Chrome).  After some searching I found that several other people have had the problem, but I didn’t see a comprehensive writeup of the solution.  Here’s what I found…

Bug description: When having a centered background image over a centered <div> (like a drop shadow over a main content <div>), the background image’s position would sometimes be “off” by 1px as the viewport in Safari, depending on the width of the viewport.  So half of possible viewport widths would show the incorrect version.  While 1px isn’t the end of the world, it can really hurt a design, and it’s nice to get center alignment in Safari/Chrome to work like Firefox/IE.

Example code:

body {
    background: #f8f8f8 url(../images/dh_bg.jpg) 50% 0 repeat-y;
}
div#everything {
    width: 980px;
    margin: 0 auto;
}

Partial Solution: First of all, always use an even-width background image – this way the rest of the browsers will get it right automatically.

To fix Safari we can apply a CSS hack targeted towards WebKit.  If your background image’s width is just a little wider than your main <div>, then this will fix it:

@media screen and (-webkit-min-device-pixel-ratio:0) {
    body {
        background-position: 49.999% 0;
    }
}

The problem with this is that if the viewport is resized to be a little larger than your div, but not as large as your background image, then the 1px problem comes back.

Real Solution:
So my solution is always use an even-width background image that is wider than the devices you want to support. I made mine 5000px wide (which is still < 1kb).  Then, the following CSS works great:

@media screen and (-webkit-min-device-pixel-ratio:0) {
    body {
        background-position: 50.001% 0;
    }
}

Hope that helps somebody.

Thanks to the helpful comments on Rob Goodlatte’s post (a JavaScript solution), which helped point me in the right direction.

2 Comments »

  1. Woodspiral said,

    May 7, 2010 @ 8:49 am

    Yes, this indeed helped me at least. I always seem to bump into this problem sooner or later when designing a layout. Thanks for the post and simple solution!

  2. Mark Hutton said,

    June 16, 2010 @ 9:09 am

    Thank you, this worked great for the very latest versions of Chrome and Safari.. it was a major bummer when I first noticed the issue & then messing around with negative margins etc to no avail – now it looks fine

RSS feed for comments on this post · TrackBack URI

Leave a Comment