Rails CSS Selector Helper
October 1st, 2007
If you’re looking for an easy way to customize css depending on the browser, without relying on JavaScript, this should be some help:
ApplicationHelper
def browser_name
@browser_name ||= begin
ua = request.env['HTTP_USER_AGENT'].downcase
if ua.index('msie') && !ua.index('opera') && !ua.index('webtv')
'ie'+ua[ua.index('msie')+5].chr
elsif ua.index('gecko/')
'gecko'
elsif ua.index('opera')
'opera'
elsif ua.index('konqueror')
'konqueror'
elsif ua.index('applewebkit/')
'safari'
elsif ua.index('mozilla/')
'gecko'
end
end
end
Then, in your layout, you should add this to your html tag: class="<%= browser_name %>"
So:
<html xmlns="http://www.w3.org/1999/xhtml" class="<%= browser_name %>">
Now, in your css, you can customise it to the browser:
.gecko button {
margin-left: -4px;
}

8 comments on “Rails CSS Selector Helper”
01
Genius!
02
The HTTP_USER_AGENT isn’t a reliable way of seeing what browser is being used.
It can be faked easely.
I believe yahoo had a way of checking the accept headers to determin what browser was being used.
03
Justin, I’m not aware of any browsers that fake the user agent. I know it can be changed, but I presume the only requests with ‘faked’ http_user_agents are from robots etc, which wouldn’t need to bother with css styles anyway. Correct me if I’m wrong….
04
Brilliant!
05
@maccman
On the contrary, it’s rather easy to change the user agent in browsers such as Firefox, Safari, and Opera. In fact, earlier versions of Opera by default identified themselves as MSIE.
06
The user agent is better than nothing, especially if you’re only using it to customize your CSS.
jQuery does some parsing of the user agent client side to provide $.browser.(msie|ff|…)
I like this approach taken to the server side, will definitely look at adapting this on my Zend Framework project.
07
IMHO a server-side UA check isn’t always a good solution: you have to take care that UA-dependent response isn’t cached and sent to another UA by a proxy.
And you DON’T want to print no-cache headers to fix this problem.
08
[…] This can be used in a variety of ways, from serving user agent specific content to adding a browser specific CSS class to avoid relying on CSS […]
Leave a Reply