Question

I need to run some css only for IE and not for other browsers. I was using conditional comments:

<!--[if lt IE 7 ]><html class="ie6 ie"> <![endif]-->
<!--[if IE 7 ]><html class="ie7 ie"> <![endif]-->
<!--[if IE 8 ]><html class="ie8 ie"> <![endif]-->
<!--[if gte IE 9]><html class="ie"> <![endif]-->
<!--[!(IE)]><!--><html class="no-ie"> <!--<![endif]-->

But this code doesn't work for IE11 and reading this article http://reference.sitepoint.com/css/conditionalcomments I discovered that earlier ie versions don't have conditional comments any more.

Then I tried to change the line 4 with this one

<!--[if gte IE 9]><!--><html class="ie"> <!--<![endif]-->

But I can see the ie class also in not ie browsers.

Is there a smart way to distinguish between IE and other browsers?

Thanks!

Was it helpful?

Solution

Answer

You can use Javascript to read the window.navigator property and get the userAgent from the resulting string like so:

var agent = window.navigator.userAgent;

if ( agent.indexOf('Trident') > -1 )
  document.querySelector('body').classList.add('ie-css');

Demo Here

If you need versions

You can use UA Parser JS to get a nice object with all the details. This would be a "safer" approach than the above but you must include the library as well:

var parser = new UAParser(),
browser = parser.getBrowser();

console.log( browser.name, browser.major );  // -> "IE 10.0"

Demo Here

Caution

You might be aware of the this but using browser sniffing is an old and bad technique out in the wild. It leads to legacy and unmanageable code very quickly. Try and avoid detecting versions of IE.

Use feature detection instead.

OTHER TIPS

In general, you should not be trying to detect whether the user is on IE11 or not. The latest version of IE is generally on a par with other browsers (in terms of HTML, CSS and JS support) for most use cases.

However, even Microsoft acknowledge that in rare cases you might need to uniquely identify it. For this, they recommend querying the user agent string. See http://msdn.microsoft.com/en-us/library/ie/hh869301%28v=vs.85%29.aspx and http://msdn.microsoft.com/en-us/library/ie/ms537503%28v=vs.85%29.aspx.

You should not need to distinguish between newer versions of IE and other browsers. IE is a much improved product these days and just as compliant to web standards as Chrome or Firefox.

The conditional comments are just to be used for IE 9 and below.

If there is something particular you need to detect for, feature detection is the way to go. This can be used for all browsers.

Have a look at Modernizr

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top