Browser selectors in CSS Ryan 19 Jul 2006

33 comments Latest by Richard Livsey

Rails must be spoiling me. Every time I have to write ugly code, I wonder: could the language be different?

I wondered just that about CSS while making some Backpack Calendar styles work across browsers. Hacks are ugly. What if I could just type a special selector, based on the name of the current browser?

@Firefox div.trash { padding-top: 5px; }

@IE6 div.trash { height: 1%; }

Sam had a great idea: “you could write some javascript that sets a class name on, say, the element based on the current browser.”

html.firefox div.trash { padding-top: 5px; }

html.ie6 div.trash { height: 1%; }

Much prettier! If only we had the time to try it out.

Update: Rafael Lima has provided the Javascript. Thanks!

33 comments (comments are closed)

Tumble 19 Jul 06

In a recent project with Smarty templates, I used a browser class to conditionally include an extra css file that contained all of the IE hacks.

I had a base css file that was perfect for FF, and then IE got an extra <style> tag that included some rules that would override things for IE. It kept them in one place and is making maintenance easier.

Justin Reid 19 Jul 06

That’s the reason people push for standards, so that you won’t have to do this. It’s a bad idea to rely on javascript to fix a css problem as javascript might be turned off. And is

html>body div.trash { padding-top: 5px; }
html>bodyIE6 div.trash { height: 1%; }

really less of a hack than this?:

@Firefox div.trash { padding-top: 5px; }
@IE6 div.trash { height: 1%; }

No. And the latter would exlude any browser not in one of those two camps.

Tumble is on the right path. Maybe a read through this, http://www.thinkvitamin.com/features/css/stop-css-hacking, might be enlightening.


Dan Cheail 19 Jul 06

Am I the only one who thinks Microsoft’s Conditional Comments is a good solution?

Anonymous Coward 19 Jul 06

“Thatís the reason people push for standards, so that you wonít have to do this. Itís a bad idea to rely on javascript to fix a css problem as javascript might be turned off.”

You can push for standards all you want, but the reality is that no browser will ever be 100% compliant and bug-free. Another reality is that even if IE, Firefox, Safari et al actually got their shit together, old browsers are sticky ó IE5.x still makes up 5% of my blog’s traffic and 9% of my employer’s traffic (and they’re both sites targeted at web professionals, not average joe surfers).

There’s absolutely nothing wrong with using Javascript to apply extra stuff to a web page, and using Javascript to apply a class to the body or html element as an extra weapon to help your page behave as expected, as long as it gracefully degrades.

Then again, I imagine these Basecamp calendars don’t work at all wihout Javascript, so bring it on!

Set a base rule that’s “the right way” (the balance between what the standards intend, and what most browsers can agree on enough for the site to be usable and legible) and then use any tools at your disposal to improve the user experience for the widest set of users.

When you no longer decide to support IE5, the legacy rules will be much easier to find too.

I usually do this with IE conditional comments, but this idea seems like a nice alternative, as long as you can live with the rules not being applied in the small percentage of browsers with Javascript off.

I’d think of it as a layer of enhancement, not a crutch to lean on.

Thanks Ryan & Sam!

Justin French 19 Jul 06

“Thatís the reason people push for standards, so that you wonít have to do this. Itís a bad idea to rely on javascript to fix a css problem as javascript might be turned off.”

You can push for standards all you want, but the reality is that no browser will ever be 100% compliant and bug-free. Another reality is that even if IE, Firefox, Safari et al actually got their shit together, old browsers are sticky ó IE5.x still makes up 5% of my blog’s traffic and 9% of my employer’s traffic (and they’re both sites targeted at web professionals, not average joe surfers).

There’s absolutely nothing wrong with using Javascript to apply extra stuff to a web page, and using Javascript to apply a class to the body or html element as an extra weapon to help your page behave as expected, as long as it gracefully degrades.

Then again, I imagine these Basecamp calendars don’t work at all wihout Javascript, so bring it on!

Set a base rule that’s “the right way” (the balance between what the standards intend, and what most browsers can agree on enough for the site to be usable and legible) and then use any tools at your disposal to improve the user experience for the widest set of users.

When you no longer decide to support IE5, the legacy rules will be much easier to find too.

I usually do this with IE conditional comments, but this idea seems like a nice alternative, as long as you can live with the rules not being applied in the small percentage of browsers with Javascript off.

I’d think of it as a layer of enhancement, not a crutch to lean on.

Thanks Ryan & Sam!

Jeff Croft 19 Jul 06

My only objection to this is that the more web developers have access to methods of targeting individual browsers with different CSS, the less incentive the browser makers have to properly implement standards in their rendering engines.

Also, I’m just not sure it’s necessary. We’re pretty much to a point with CSS where it works well and reliably in everything expect Internet Explorer. And Internet Explorer already offers a good and elegant solution (conditional comments).

Matt James 19 Jul 06

I also use conditional statements to handle this same thing. While they propose an interesting take on it, I don’t like the idea of running javascript for something like this. I guess it’s my gut feeling that a straight CSS solution is better fitted for affecting layout than, say, using JS. Now, I have no qualms with using JS to do stuff, but when you have conditional statements sitting there and IE is the trouble-maker, I lean toward using them to just pick it off rather write some JS to take care of it.

Having said that, IE sucks and needs to truly adopt CSS2 and PNGs sometime this century!

soxiam 19 Jul 06

Nice thought except it doesn’t have a chance in hell in becoming standardized by organizing bodies or browser makers. Of course we wouldn’t even be having this discussion if all browsers would just follow the standards.

mini-d 19 Jul 06

No, i preffer this unsolved and non complete shit of CSS support than having to write 8-9 browser names for the same action. As Zeldman said: to the hell old browsers.

Browsers nowadays are getting better. Just look at Safari, Firefox and Opera, the listeners, but we have to yell and report for fix and implement things.

The last webkit at safari is mint for my mouth. Firefox stuck in a long thinking, no CSS support as Safari does. Opera has good support on, but I’m seeing more active to the people of Apple than the Opera’s guys.

They’re developer like us, if we yell for fixes they, maybe, will listen us and fix it up.

Forget IE, that’s a browser for 5 year old kid.

Matt 19 Jul 06

Ideally you write code that works on most browsers, then use this method to fix browsers that are being a fussy.

I use ColdFusion, and it supports CGI.HTTP_USER_AGENT to detect user agents serverside (no issue if javascript is off).

Using this method, you could, for example, set if they are using ie, and then the document would start using the body#ie selectors. If the browser works fine with your css, without any special selectors, you just make it so the browser detection doesn’t set an id for body, and then the browser just uses the default css.

Jeff Croft 19 Jul 06

Matt:

How is that any better than using conditional comments? Conditional comments are the official and recommended way of handling IE inconsistencies. Any other method better have strong advantages if it expects me to use it instead.

Rafael Lima 19 Jul 06

For those who want to use this new solution:
http://rafael.adm.br/css_browser_selector/

Thanks!

Matt Vanderpol 19 Jul 06

Another problem I’ve run across with using the CSS hacks for IE is that IE 7 understands most (all?) of them and you can’t use them to hide styles anymore. Unfortunately you still need to workaround different CSS implementations so you have to keep at least some separate styles for IE vs Everything Else. Maybe some of this will be fixed before the final release but I’m not holding my breath.

I think that the only solution that will work moving forward is to use the conditional includes. It’s what Microsoft says to do to solve the problem and I think that it’s the only thing that we can count on to continue to work.

All that being said, using JavaScript to add a class seems like an interesting idea and it definitely has parallels to the conditional include concept.

Rad Smith 19 Jul 06

I agree with Jeff that conditional comments are the ideal solution. Rarely do you need to have specific styles for Firefox, Safari, or Opera. IE6 is generally the issue, and conditional comments allow for a clean fix that doesn’t rely on parsing bugs.

scott 19 Jul 06

Dan Cheail: nope.

really, i’m surprised conditional comments are not more well-known (or, at least, more often used). then again, i feel the same way about 90% of what i do in terms of HTML/CSS.

Seth Thomas Rasmussen 19 Jul 06

<link … href=”cool-kids.css” />
<!—[if IE]><link … href=”ie.css” /><![endif]—>

You just write standard CSS, and JavaScript is completely unecessary.

Jeff Croft 19 Jul 06

“Another problem Iíve run across with using the CSS hacks for IE is that IE 7 understands most (all?) of them and you canít use them to hide styles anymore…”

Except that doesn’t apply to conditional comments…

*broken record*

Christian Augustin 20 Jul 06

The idea of using “browser classes” at the html element is interesting, because it can help simplify the handling of smaller differences between specific browsers (and all of them have their little quirks).

I agree that MSIE/Win in its various versions should be handled with conditional comments, because they are functional with JavaScript off — but even with conditional comments you often have to use dynamic properties, and therefor JavaScript on, to get things properly fixed in some very weird cases.

Keep on your good work. Its a pleasure to read Signal vs. Noise!

glasser 20 Jul 06

Rafael, if you’re going to do this, you should probably key off the rendering engine part of the string, not the browser name, so “AppleWebKit/” instead of Safari and “Gecko/” instead of Firefox. Your page didn’t work in the first two browsers I tried: NetNewsWire (which should render like Safari) and Camino (which should render like Firefox).

(I put the slashes in there because WebKit browsers say “(KHTML, like Gecko)” at some point but you wouldn’t want to treat that as Gecko.)

Su 20 Jul 06

There’s already pretty much a framework for this, no? But rather than only being for extensions, have the browser check for rules in the form “-browserprefix-standardselector” which would override the matching pure-standard selectors. (I think Gecko already does this with its prefix, actually.)

So:

margin : 5px gives every browser 5px margin initially
-moz-margin : 7px overrides Mozilla browsers to 7px
-o-margin : 9px overrides Opera to 9px
-ie5-margin : 14px overrides IE5 to 14px

No significant chance for conflict, no Javascript/PHP/whatever dependence, and completely extendable, since the CSS standard doesn’t care about or track these; it’s the browser’s concern. As a bonus, this wouldn’t require adding anything to the spec. Because really, even Microsoft moves faster than the W3C.

Conditional comments as they exist right now(IE-specific) aren’t an ideal solution, just a (very very) common one. The other browsers have bugs or at least divergent behavrior, too. You may not hit them nearly as often, but they do exist.

Dan Glegg 20 Jul 06

I generally write one “main” layer of CSS targeted at the well-behaved browsers (safari, firefox and opera) - this is possible to do in one set of styles with a bit of tinkering.

Then I have a layer of overrides loaded in the insolent, ADHD browsers (Internet Explorer) which tweak and break the existing rules. The hacks layer is loaded by a small javascript, which may be filthy but there’s far worse things being done to innocent browsers out there.

Rafael Lima 20 Jul 06

glasser,

Thanks for your contribution, version 0.2 is available!
http://rafael.adm.br/css_browser_selector/

Jeff,

With IE conditional comments you can ignore the version 7 by doing that:

Blair 20 Jul 06

How is this *any* better than the browser-sniffing techniques of old? What’s to stop Browser X from simply identifying itself as Browser Y to get around having to properly program one area of the CSS spec, only to seemingly bungle another area simply because it’s receiving rules for another browser?

Now, I realize that Opera or Firefox or Safari could just as easily decide to implement conditional comments tomorrow, and start reading rules meant for the Explorers… but that’d be a pretty poor decision on their part (not to mention *really* unlikely).

The fact of the matter is, conditional comments work to handle IE/Win 5 through 7. That covers roughly, what, 80-90% of *all* installed browsers. Firefox, Opera, Safari, OmniWeb, and newer versions of Netscape cover nearly all of what remains, and all of them handle CSS *really* well.

So what leaves us browsers that people are using by choice (e.g., they know exactly what they’re getting themselves into — iCab pre3.0 beta users, here’s to looking at you), the few who haven’t upgraded because they don’t know any better (they’ll be forced to upgrade the next time they buy a new computer — if the fact that “nothing seems to work right” doesn’t force the issue sooner), and those who are working in corporate environments that force the usage of old browsers to support old intranet applications (who have the choice to run a second browser for everything else).

The aforementioned represent a rather miniscule percentage of the browsing public. Small enough that destroying what we’ve worked so hard for — consistent support of standards by the browser makers — isn’t worth supporting them with some sort of javascript-browser-sniffing-stupidity that’s really just meant for the lazy, whether they be designers, developers, or the browser makers themselves.

beto 20 Jul 06

Conditional comments is where it’s at to address these issues. For a good number of reasons (not to mention it being implemented by MS itself, and therefore, likely to be supported on future versions of IE). It won’t break your validation either since all other browsers see it as an HTML comment. I decided to take the conditional comments route some years ago since it helped me keep things clean in CSS, so I can focus on creating CSS code the right way and then address all IE’s quirks on a separate CSS file only IE will read. Still, of course I’d rather wish not having to spend time doing this… there are plenty more interesting things to do in life than spend your time miserably in front of a bratty browser who refuses to play along.

Abu Hurayrah 20 Jul 06

A quick look at A List Apart will show you that there are methods by which wide cross-browser compatibility can be achieved while maintaining good standards compliance. They also put an emphasis on sticking with semantic markup (e.g., avoiding excessive divs for styling purposes).

The part that astonishes me the most is that the quagmire we’re in regarding browser support for standards & browser-specific hacks is specifically because people were so lax about following standards. How many of the changes in IE7 are directly related to features & techniques implemented years ago in other browsers with more active development? Would the focus on IE7’s standards compliance (not perfect, but much improved) be nearly as strong if not for the existance of browsers like Opera & Safari (and it’s brother, Konqueror) that strive to be as compliant as possible? These are not minor points

If it weren’t for standards in the first place, and the subsequent following of these standards, we wouldn’t have web pages viewable on portable devices, via alternative methods (e.g., screen readers), or even on different platforms (Windows, Mac, & Linux). So, sticking to & following standards is in everyone’s best interests…except, perhaps, corporations that derive their revenue from vendor lock-in. Pity them…

Andy Kant 20 Jul 06

I also vote for conditional comments. It is the cleanest solution, most maintainable, and is future proof against IE7.

Dan Grossman 20 Jul 06

Theyíre developer like us, if we yell for fixes they, maybe, will listen us and fix it up.

Don’t you wish the W3C would consider that? These standards we push browser vendors so hard to follow are incomplete, contain conflicts, and don’t have well-defined DTDs. The validators we judge ourselves on make guesses as to the meaning of these standards because they can’t get the people writing the standards to fix their conflicts.

The standards-creating groups at W3C don’t listen to developers, don’t listen to users, and don’t listen to the other W3C groups that work with those standards. What we get are these messes like XHTML 2.0.

gwg 20 Jul 06

I guess that I’m not sure why web apps should ever use workarounds like this. 37s products in particular are not pixel-perfect, nor do they need to be. Why quibble over a pixel or 5 here and there?

There’s always a way to achive nearly identical results without IE comments or hacks.

It makes more sense to me for B2C sites that heavily rely on pixel perfect layouts.

Klaus Hartl 20 Jul 06

If you know CSS and know what you are doing you won’t need a hack for Firefox, Safari and Opera in 99.5% of all cases (if you can live with some inconsistencies at form elements that is).
For the other 0.5% you could find another solution than hacking.

For IE we have Conditional Comments. Relying on JavaScript for some hacks makes the whole hacking thing even worse.

I recommend reading Tantek (the inventor of the CSS hack by the way) about hacks here: CSS Hacks And Other Good Intentions

Mark Priestap 21 Jul 06

I agree that IE conditional comments are the best thing to use for IE, but what about Safari? What if you want to style form elements like textboxes and Safari doesn’t let you? This might be a nice little way to do that cleanly. If people have javascript turned off…big deal. The texboxes will still show up.

Christian Decker 21 Jul 06

Ok I know: most of you have a project to finish and some precise deadlines, but let’s think about it, is writing duplicate code not a burden for us, and a reward for all those browsers that do not comply with standards (ahem, IE…)?
Do we really want to reward people using crappy browsers, or do we want a consistent working environment?

Richard Livsey 22 Jul 06

I just created a quick Rails plugin so you can do the same thing but in your views. So you can do:


or

Pretty simple at the moment, but could be useful to build on.
There’s more here.

Richard Livsey 22 Jul 06

It stripped the example, that should have been:

[% if browser_is? :mozilla %] … [% end %]

or

[%= browser_name %]

Replace the []’s with angle brackets and you get the idea.