Valid CSS hiding from IE6

We interrupt the regularly scheduled baby photoblog for some web dev stuff.

It may not come as much of a surprise that IE has trouble with some css elements, but I’ve just run across a really nasty one and a reasonably good solution.

I was trying to use a DHTML calendar (not on this site though) that is completely dynamically created dom objects, styled with CSS. So far so good, it works on my test browsers, and amazingly enough, it ‘works’ with IE6.

Unfortunately the background images flicker, as others have figured out. If you have a background image on a dynamically created node, the cached version of the background image is not used, and the image is downloaded again from the server. Over and over. I was seeing the background for table cells download on every mouseover event, and for a calendar, that’s a lot of cells and a ton of requests. Thankfully, most of the requests where getting a 304 not changed response, but it’s still not nice to the server to be requesting an image 50 times when it should just be requested once.

So, the background images had to go. But only for IE, and I couldn’t change any of the html generated, since it wasn’t in my library. The only saving grace was that all of the items that I needed to change had class definitions.

Enter the attribute selector bug. I’m not normally one to code to browser bugs, but since I’m working around a bug, hopefully they will fix all of these at the same time. Or none at all.

The basic version of the attribute selector bug is that when IE/Win or an old version of Opera (3.x) hits css like

div[id] { }

it completely ignores it. Everyone else applies that css to a div with an id attribute. That’s pretty general, and not of a ton of use, except that there are specific equivalences of common class/id methods and selectors. (see the spec)

Classes are a space separated list of attributes applied to an element, and an id is a single exact attribute applied to an element. Thankfully, there are two versions of the attribute selector that support those exact semantics — both of them completely ignored by IE6.

/* Shows up everywhere */
div.classname {border: 3px solid green; }
/* Hidden from IE/Win */
div[class~=classname] { border: 3px solid red; }
/* Hidden from IE/Win , the same as div#idval */
div[id=idval] { background: #ff0; }

See Example

The class selectors are more effective, since the attribute selector version is interpreted as more specific than the more common dot notation version. The id attribute selector, unfortunately, does not take precedence over the has notation version. It is still possible to send additional css to Mozilla/Safari, IE just won’t get any.

While this is a browser bug exploitation hack, It’s simple, effective and what’s more, it validates.

No comments

No comments yet. Be the first.

Leave a reply

You must be logged in to post a comment.