Camen Design

c share + remix

Targeting Browsers With CSS Using mod_rewrite

Ⅰ. the Need for CSS-Hacks

In a world of imperfect browsers, the CSS-hack can be both a beautiful thing, and also an ugly thing too.

It is unavoidable that at some point some feature or design you wish to implement hits a limitation or parsing / rendering bug of one (or more) browsers you are supporting.

If this has never happened to you; well done—you’re an IE only web-developer who’s never stepped outside of Microsoft software, nor table-based design. You’re probably confused by the term CSS.

If, however, you do not own that privileged position of ignorance, everybody comes across the need to target a particular bit of CSS to a particular browser.

Ⅱ. the Question of Maintenance

There are many arguments about if CSS-hacks should be totally avoided, embraced, or properly managed somehow.

Firstly, to think they can be avoided is naïve. I have a website that only supports Acid2 compliant browsers, uses CSS3 liberally, and doesn’t support IE one iota—and still I have CSS-hacks to deal with browser idiosyncrasies.

The next two lines of argument are either a) just embed hacks in your normal document—it’s less maintenance to only edit one document and b) keep hacks to a separate file where they can be managed individually, ideally using conditional comments to target IE specifically or Javascript to correct behaviour.

Embedding CSS-hacks in stylesheets increases maintenance by making them an integral part of testing in all browsers. CSS designed to correct one browser may have undesired effects on another browser. Or a hack that has been used before, may no longer work on a newer version of a browser, but now you have to scramble to somehow support both browsers.

A hack is anything that has the potential to fail disastrously
each time something changes expectedly.

Kroc Camen

Having to make corrections to your whole stylesheet to please one browser, is unnecessary maintenance. Having all your failure points in one document is not less maintenance. I have not very fond memories of having to rewrite large portions of a stylesheet because of being unable to please one browser without effecting sic others.

The answer therefore is to tie CSS-hacks—or at least alternative CSS—directly to the browser it fixes, so that it does not becoming a ticking time bomb for other browsers and future versions.

In the case of IE, conditional comments give very precise targeting capabilities. Conditional comments are an excellent solution for applying alternative CSS, rather than relying on CSS-hacks preying on broken parsing. However, there are a couple of let-downs:

Having to maintain HTML because of a browser, is like suddenly waking up one day to discover that the letter Z has been officially depreciated by the European Union and now you have to update all your documents to conform.

Your HTML, like diamonds, should be forever.

Kroc Camen

Lastly, using a Javascript fix is only increasing the length of thread you have to follow when something breaks. If suddenly you find that a CSS property you apply does not have the expected behaviour in IE, but gives different results with the Javascript fix on, and then off: you now have a maintenance nightmare that involves back-tracking through ‘x’-tons of Javascript, that likely, you didn’t write yourself.

What if a new version of a browser comes out and your Javascript fix doesn’t work with that browser, but also, the site design won’t render correctly without it? Now you’re forced to either remove the Javascript and do the CSS again, properly, from scratch; or update the Javascript with all the work that entails.

A solution is needed that:

  1. Works for all browsers and does not rely on browser-specific capabilities to implement
  2. Negates the need for CSS-hacks, and instead encourages alternative CSS
  3. Targets browsers/versions specifically or according to a range
  4. Does not fail when a new browser or version arrives on the scene

Ⅲ. the Answer Is Still Targeting

We all know that user-agent targeting is bad. It defeats the purpose of having standards to work across all browsers. However, thus far, we have, by proxy, ascertained that there are two types of CSS:

The maintenance problems so far outlined are because there is no clean separation of these two—except for IE conditional comments, with the acknowledgement that they are an incomplete solution.

We have also ascertained that browser-specific CSS is eventually required given imperfect browsers. You can either choose to compromise on your design to avoid this, or compromise on the browser and keep the design. Either way, the end-user should never be compromised on.

It’s important to state that writing standards-compliant, proper CSS is always desired. Legacy browsers are exactly that: legacy. Therefore a solution to dividing the two types of CSS must primarily acknowledge that proper CSS comes first and does not require any maintenance going forward. The current solutions mentioned earlier do not give weight to the better CSS over the bad CSS. Basically, with a perfect solution, a perfect browser would never parse any hack or CSS intended for only one browser—it would be ignorant of legacy browsers.

The important thing with User-Agent targeting is the ability to also not target user-agents. Some believe user-agent targeting to be a form of quicksand that has you chasing after every browser ever made.

A browser that applies the standards, and requires no browser-specific CSS to render the design, does not need to be targeted. No solution is actually needed.

Kroc Camen

My proposal is therefore a solution only for legacy browsers. If a browser does not need browser-specific CSS to get it to render a design right, then it requires zero maintenance on part of this solution. There is no interference by the solution to browsers that do not need it.

The Solution

Apache’s mod_rewrite module allows us to take a file requested by the browser, and provide a different file instead, based on some matching or non-matching criteria.

What if we had a “fixes.css” file that was different for each browser that needs to be targeted, but void by default so that any browser that doesn’t need fixes, doesn’t get any?

We start with two stylesheets declared in the HTML head element:

<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/fixes.css" />

You write your main stylesheet using absolutely no CSS-hacks or browser-specific workarounds. Write for the future. As more and more browsers come on board with Acid 2 / 3, CSS3 compatibility &c. they should automatically fall into working with your site—zero maintenance needed.

Remember, this mod_rewrite solution is only to bring non-complaint browsers into spec. Ideally, for example, you’d write your stylesheet to meet Acid 2 capabilities and when IE8 is released the site just works, and the IE7 workarounds stay with IE7.

The actual ‘fixes.css’ file itself is, therefore, completely blank.

In your ‘.htaccess’ file use the following two lines to target a browser and rewrite the ‘fixes.css’ file to a browser-specific version: (IE7 in this example)

(Assuming you’ve already got “RewriteEngine on” in your ‘.htaccess’ file and “RewriteBase” if needed.)

RewriteCond %{HTTP_USER_AGENT} MSIE\s7\.(?!.*Opera)
RewriteRule ^(.*fixes)\.css$ /$1.ie7.css [L]

This selects a user-agent containing MSIE 7. as long as it’s not followed by Opera at some point (to ignore Opera spoofing as IE). The ‘fixes.css’ file is then rewritten to a ‘fixes.ie7.css’ file where you may store the IE7 specific fixes you need to apply.

Now users of IE7 will receive a different ‘fixes.css’ than users of any other browser.

It’s a bit like having a user style on your own website. You can apply a CSS “patch” to the site for specific browsers, keeping your main stylesheet legacy free and future-facing.

Potential Uses

In short, old browsers shouldn’t prevent you from using the latest and greatest that up-to-date browsers offer. It’s up to you to keep legacy where it belongs.

Addressing Concerns

“Aha!”, I hear you say. “But surely this creates more maintenance, now we have many CSS files!”

With this solution, when you make a browser-specific correction, you only need to test in that browser itself. Less maintenance. Without this solution, a browser-specific fix also gets parsed by all browsers, and you need to test them as well. More maintenance.

“But now you have to maintain the ‘.htaccess’ file!”

As browsers get more capable, the less browser-specific CSS you will need to target, if at all. An old browser doesn’t stop being an old browser. As long as you’re not changing the HTML, this solution can safely bit-rot without ever being looked at.

This solution also allows you to react smoothly and quickly to an unexpected regression between versions of browsers. Imagine you try out a beta browser like Opera 10 or Firefox 3.1 and you suddenly find your design breaks with it. You can—without touching a line of your existing main stylesheet—add two lines to the ‘.htaccess’ file to detect the new browser, and then develop, on a new sheet, the necessary fixes without compromising any of the existing CSS. You can then choose to leave that as is, or then once working roll it back into the main sheet. This is significantly less panic-prone than having to apply fixes for an unreleased browser to a live, perfectly working stylesheet.

Imagine you want to stop supporting a legacy browser. With this method, you remove the two lines in the ‘.htaccess’ file, delete the specific ‘fixes.css’ file and that’s it—browser unsupported. Without this solution, you would have to manually unpick the CSS-hacks from your main stylesheet and slowly rub-out any influence that browser had on the design of the CSS. Sometimes the only way to truly remove a browser’s influence from a large bit of CSS is to simply rewrite it (due to all the extra capabilities opened up with newer versions that you should now be making use of).

“What about people/browsers spoofing user-agents?”

Not a problem. Seriously. Writing the right regex to spot lame attempts at spoofing is not difficult. Many browsers add like Gecko / khtml despite this being patently false. It’s becoming more common even to add Firefox into Gecko browsers given Firefox’s weight in the market. It’s sad, really, that some have given in to this pathetic behaviour.

If you’re literally browsing with a completely false user-agent by default, you are a) 0.01% of the population and b) have a personality disorder, or something. Spoofing has its uses, but it’s legacy as well and should be sent the way of the dodo (if browser vendors stop with this ridiculous behaviour of saying they’re engines they are nothing like).

In other words, the answer is: learn regex.

The HTTP-Request Tax

I hate wasting HTTP-Requests. If you want a fast site, it’s not bandwidth or file size that matters; no, it’s the number of HTTP-Requests. Each one could have potential delays up to 1–2 seconds in worse cases.

So there’s a severe flaw with this solution, the browser has to fetch two CSS files, even if the browser doesn’t need any fixes. This is a tax on good behaviour!

There is a workaround for this that presents only one stylesheet to compliant browsers, but two stylesheets to those browsers that need fixes.

If you present just one stylesheet in the header:

<link rel="stylesheet" type="text/css" href="css/main.css" />

And then, in the ‘.htaccess’ file, redirect ‘main.css’ to the fix sheets, for those legacy browsers:

RewriteCond %{HTTP_USER_AGENT} MSIE\s7\.(?!.*Opera)
RewriteRule ^(.*)main\.css$ /$1fixes.ie7.css [L]
# ...

# after legacy fixes, redirect ‘main.css’ to the actual main sheet ‘_main.css’
RewriteRule ^(.*)(?<!_)main\.css$ /$1_main.css [L]

And at the top of each fixes sheet, just simply import the main stylesheet.
(The main sheet uses a dummy name to prevent the @import from getting stuck in an infinite loop.)

@import "_main.css";
/* browser specific fixes here... */

This way, a browser that needs correction gets the fixes sheet first (with the main stylesheet imported at the top) and a browser that doesn’t need any fixes just gets the main sheet alone.

Example Reference

For those with worn C and V keys, here’s some additional rewrite conditions to select particular browsers (Add the RewriteRule according to your chosen method). If you’ve any suggestions for good examples, do send them my way

If you want some sample user-agent strings to work out the right regex needed for a particular browser, here’s a good list.

Internet Explorer (Any Version):

RewriteCond %{HTTP_USER_AGENT} MSIE\s\d\.(?!.*Opera)

Change \d to any number to select a particular version

Internet Explorer, Version ‘X’ and Below:

RewriteCond %{HTTP_USER_AGENT} MSIE\s(\d)\.(?!.*Opera)
RewriteCond %1 <=7

Change the <= to >= to target a particular version and above.

Firefox, Versions Before 3.0:

RewriteCond %{HTTP_USER_AGENT} Gecko/(\d{8})(?!.*Opera)
RewriteCond %1 <20080529

Do not ever try detect Firefox using “Firefox”. Remember that Gecko, the rendering engine that powers Firefox is used in many other browsers too that would have equal capabilities, such as Camino. Many browsers now spoof as Firefox too, so always detect using the Gecko date of the browser in the user-agent.


RewriteCond %{HTTP_USER_AGENT} iPhone|iPod