Tuesday, June 23, 2009

Combining CSS and user agent sniffing

Avoid sniffing if you can
User agent sniffing is bad and that's known. So avoid it if you can.

However, in some cases a browser is just acting weird and you cannot ignore that, it needs some specific CSS instructions. Internet Explorer 6 and 7 are prime examples here.

The old days: CSS hacks
In the past, this was resolved with odd CSS filters (better known as hacks), constructs that were known to work in some browsers and be ignored in some other browsers. To do this well, you need to know about the quirks of all browsers. This is not scalable, with new browsers coming out all the time.

Alternative: Sniffing and CSS classes
Here's an alternative: Use server-side agent sniffing and put the results in a class attribute in the HTML. This allows you to write CSS rules like:
.Browser-Opera ul.ModList li {display:block}
or even:
.BrowserOS-MacOS-10.Browser-Firefox-3-5 li.FooBar {margin-left:2px}
To see this in action, have a look at the source code of the PensioenPage site:
www.pensioenpage.com
or, with indentation enabled in the source code:
www.pensioenpage.com/?_indent=true
Note that the user agent sniffing we implemented has more than 160 unit tests, detecting (Mobile) Internet Explorer, Opera Desktop/Mobile/Mini, Firefox, the old Netscape browsers, Chrome, Safari, Maxthon, etc.

Operating systems detected include Mac OS X, various Windows versions, BSD variants, Solaris, Linux, the iPhone OS, etc.

Finally, the browser engine is also detected, allowing rules like this one:
.BrowserEngine-Trident div.Tip {padding:0}

No comments:

Post a Comment