views:

398

answers:

4

I've seen people doing things like this in their HTML:

<!--[if IE]>
  <link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->

Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?

Edit

Thanks Ross. Interesting to find out about gt, lt, gte, & lte.

+10  A: 

This works across all browsers because anything except IE sees <!--IGNORED COMMENT-->. Only IE reads the comment if it contains a conditional clause. Have a look at this article

You can also specify which version of IE. For example:

<!--[if IE 8]>
<link rel="stylesheet type="text/css" href="ie8.css" />
<![endif]-->
Ross
To add a bit, this is officially supported by MS, and is generally considered a developer best practice in cases where you absolutely have to target IE (vs. all the ugly CSS hacks web devs used previously). Here's an MSDN article w/full syntax: http://msdn.microsoft.com/en-us/library/ms537512.aspx
joelhardi
+1  A: 

Further to Ross' answer, you can only target the Internet Explorer rendering engine with conditional comments; there is no similar construct for other browsers. For example, you can't write conditional comments that target Firefox, but are ignored by Internet Explorer.

The way I achieve the same effect as your example above is to sniff the user agent string. I then deliver a suitable CSS file for that browser. This isn't perfect because sometimes people change their user-agent string for compatibility.

The other way to target different browsers is to utilise browser specific hacks. These are particularly nasty because they usually rely on bugs in the browser and bugs are liable to be fixed!

User-agent sniffing is the best all-round solution in my opinion.

Simon Johnson
+1  A: 

If you can use Javascript, there are several options:

navigator.appName
navigator.appVersion

link

Or something more robust by using a library such as jQuery.

Finally, you could use the BrowserDetect object from QuirksMode.

Once you have the browser name and version, you can then insert HTML to link to a style sheet or include other tags.

sock
A: 

Conditional comments are purely for IE (version 5 and later). The official Microsoft documentation is here. If you are going to use them the best strategy is to conditionally include external stylesheets or javascript files after your normal includes. This means that on IE your IE-specific code will override everything else. On any other browser the code will be treated as comments and ignored by the parser.

domgblackwell