Monday, December 20, 2010

Thursday, December 16, 2010

How to serve different stylesheets only to Safari and Chrome

Well, as you already know that to support Internet Explorer we often serve different CSS files using IE’s special conditional-comment syntax, which is great in terms of having clean and maintainable stylesheets throughout your application, it also mitigates the need of writing CSS hacks which often makes the stylesheets messy and becomes a maintenance nightmare later. You may argue that serving different CSS files only to IE is certainly not an elegant solution and of course it is not, it still requires that extra effort and extra bandwidth for users of Internet Explorer, but it’s somewhat the most practical or possibly the cleanest solution that you can have.

As there’s no way to target other browsers using conditional-comment like thing then how would you do it if you ever(though unlikely) have a need to serve different CSS files to some of the modern browsers? Well, seems like I have a solution for you. Recently, I stumbled upon a code while doing “view source” (I do it all the times and have found it pretty useful), which had something different that caught my eye on. I don’t know whether this is a well documented or a known thing, but this is something I have never seen before, so I thought it might be a good idea to document it here, in case it helps someone. By the way, keep in mind that this only works in Safari and Chrome as because both browsers share the same rendering engine, so assuming that all webkit based ones will have the same behavior. Opera, Gecko and Internet Explorer do not exhibit this behavior as I have found.

It appears that webkit ignores “text/css” value of the “type” attribute of tags as long as you have “rel=stylesheet”, I assume that it depends on mime-type instead of the type mentioned in the tag itself. The following code will load the stylesheet file in Safari/Chrome but none of Opera, Gecko(Firefox) and Internet Explorer( 6, 7 and 8 ) will even load the CSS file:

You can have anything in the “type” attribute like “text/mycss” or “text/webkit” all will work. By the way, removing the “type” attribute loads the file in other browser’s too, so to prevent that you got to specify something different albeit an incorrect type. This is a bit whacky or clever way to target webkit specific browsers.

Finally, the question is that do you ever really need this ? I don’t think so, mostly 99% cases you don’t need to target webkit browsers specifically, they have an excellent support of web standards and my experience says that most of the things just work out of the box in webkit and gecko. So this tip is for that 1% edge cases where you might need this.