Search code examples
htmlcssinternet-explorerconditional-comments

Different css for IE browsers


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!


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.