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?
The concept of feature detection The idea behind feature detection is that you can run a test to determine whether a feature is supported in the current browser, and then conditionally run code to provide an acceptable experience both in browsers that do support the feature, and browsers that don't.
To detect user browser information we use the navigator. userAgent property. And then we match with the browser name to identify the user browser. Now call this JS function on page load, and this will display the user browser name on page load.
Open the Google Chrome page Open the Google Chrome page of the specific HTML that you want to inspect. Press "Control" + "U" on the keyboard and a separate page with the source code appears.
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 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/.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With