Search code examples
cssuser-agent

How do I detect the user’s browser and apply a specific CSS file?


I need to detect the browser and apply the matched CSS file.

I have created 3 css files: __ie.css, ff.css, opera.css. Now I need to detect the browser in order to include the good one.

I know this

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

But how do I do the same with Firefox and Opera/Chrome?


Solution

  • If you have to detect browsers just to apply CSS, then you might want to rethink your CSS before going to browser-specific stylesheets. All it takes is for one browser to mimic another's user agent string, or a new version to be released, and everything breaks. Use the current standards and validate your code (http://validator.w3.org/), and you'll have to worry about far fewer cross-browser issues. Even just using <!--[if IE]><![endif]--> without a version number could break the layout in later versions.

    That being said, if you want to style the page differently based on what CSS features are available, take a look at Modernizr. This way, you're only checking features, which won't be broken if a new version of the browser is released.

    If all else fails and you really need to detect the visitor's browser, try jquery.browser. It's built into jQuery, and is simple to use. http://api.jquery.com/jQuery.browser/.