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

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/.


The closest you can come with pure CSS is with feature queries. Instead of detecting the browser type/version, it allows you to check if a specific property/value combinations are supported by the browser.

The following is an example of using the transform property for vertical centering. If the browser doesn't support transform, then we don't want to adjust its positioning:

@supports (transform: translateY(-50%)) {
    .foo {
        position: relative;
        top: 50%;
        transform: translateY(-50%);
    }
}

Browser support for Feature Queries


If you need to browser detect for Firefox, Opera and Chrome, then you're doing something wrong. The same CSS should work in all of them.

There are exceptions to this of course -- all the browsers have missing features and bugs which don't appear in the other browsers. An example would be text-overflow:ellipsis which isn't supported by Firefox.

However, if you're sticking to commonly used features, these cases are few and far between, and in general, you really shouldn't need to do browser detection these days, except for various versions of IE.

If you're not sure whether the features you want to use are supported by most browsers, you can find out at CanIUse.com or Quirksmode.

If you're using seriously cutting-edge features, then yes, you will have problems with cross-browser support. But in this case it's generally better to do feature detection, using a product like Modernizr, rather than browser detection, since this will be a more reliable way of ensuring you cover all browsers and all versions, including future versions (which is an inherent weakeness of browser detection).

Tags:

Css

User Agent