CSS HTML Class – Browser and Operating System

I was trying to find a good snippet of code that would help me style the different browsers better.  I’ve used all the attribute hacks before but one thing I’ve run into lately is the fact that Chrome and Safari end up interpreting and displaying input tags differently even though they are both Webkit based. There were not individual attribute hacks that I could find, but I was able to find this beauty over at http://github.com/rafaelp/css_browser_selector. I’ve also added the code to my Snipplr Arsenal so you can get it over at http://snipplr.com/view/23988/adds-os-and-browser-class-to-html-tag/

/*
CSS Browser Selector v0.3.4 (Sep 29, 2009)
Rafael Lima (http://rafael.adm.br)

http://rafael.adm.br/css_browser_selector

License: http://creativecommons.org/licenses/by/2.5/
Contributors: http://rafael.adm.br/css_browser_selector#contributors
*/
function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);

That code makes it so I can even validate my CSS and get rid of my attribute hacks. The code adds a bunch of different classes to your HTML tag. It adds the Operating System, the Browser, the Browser Version, and if Javascript is enabled or not. You can do a lot with that info. I was able to then create a Chrome specific style for my stylesheet. Love this code. It has been added to my regular arsenal of code.

Just include that code in your head or reference it as a separate file in your head. I prefer a separate file, but to each their own.

Leave a Reply