Life is a Mystery

2 February 2011

Off by one pixel

I’ve been working on a theme for WordPress and ran into an interesting CSS positioning bug in WebKit today. For some reason an background image I was positioning with “center” was not lining up with a div being centered by “auto”. No problem in Firefox, but in WebKit the two would jump out of alignment with one another as I changed the window size. They would pop in and out of alignment by a single pixel.

Luckily I found a brilliant post about the problem that contained a simple demonstration. Even better, the author offered this suggestion:

In some cases, realizing what causes the problem is a clue towards a workaround. For example, you could use a wrapper div that has the background image, and is exactly as wide as the background image itself. Center it with auto margins, and there should not be any offset bugs.

That took me a few readings, but it resulted in this change to my own CSS code. Since I already had a “wrapper div” I just changed it so that instead of positioning the background image like this:

   background-image: url(images/rea-back.png);
   background-position: center top;

I used an explicit width and auto like this:

   background-image: url(images/rea-back.png);
   width: 1020px;
   margin: 0px auto;

Problem solved! Gotta love the web! Oh, and yes, the bug has been reported to the WebKit project.

one pixel

Comments are closed.

Eric Celeste / Saint Paul, Minnesota / 651.323.2009 / efc@clst.org