Friday, February 12, 2010

CSS: Negative vertical margins can be unpredictable

Here's the scenario:

We have a header image that goes across the page. It has our logo on it, plus some nice curvy lines at the top and the bottom.

When we print the page, however, we don't want the bottom line to appear so there's a second image that should print.

I placed the second image into the HTML with an alt tag of the organisation name. The first image is a background image. In the CSS for the page (screen) I could either use display: none or negative margins to hide the second image.

I figured that non-visual users would need to know it is there. (However, I will review the code to see whether it is actually adding anything. I think we have our name in a hidden h1 tag so we can probably just use display: none.) display: none hides elements from many screen readers as well as browsers.

The commonly used alternative is a negative margin. As the image I was hiding went across the top of the page I thought margin-top: -9999px; should do it. It worked in IE but in Firefox and Chrome the bottom of the image peeped down over the top of the background image. I tried ex instead of pixels but the result was pretty much the same.

In the end I used margin-left: -9999em (em measures width; ex measures height) which worked in all browsers.

Another alternative, as recommended by 456 Berea Street is to use

position: absolute; 
left: -9999px; 

I'm not sure whether this is better than my solution. I suppose it's probably safer as it uses absolute positioning. But as the measurements (9999ems) are so massive I can't see how there is any danger of the image somehow ending up on screen if other elements move around. As it works, and is one line of code smaller, I think I'll stick with margin-left: -9999em  for now.

No comments:

Post a Comment