Conditionally Load Stylesheets in IE11

Ever had a client ask for a new, modern site but require compatibility with Internet Explorer (IE) 11? Seems counterintuitive but believe me they’re out there. Usually these sorts of people are constrained by their company or organization to support a browser even Microsoft recommends against using.

How would you handle applying a fix to the inevitable visual bug in IE? In the past, there was a really simple way to only load certain files or content in IE. For whatever reason Microsoft decided to remove this helpful condition. Look how easy it used to be:

    
HTML
<!--[if IE]> <link href="/path/to/ie.css" rel="stylesheet" /> <p>Only people using IE see this message.</p> <![endif]-->

Internet Explorer 11 doesn’t support the conditional tag any longer. Luckily, there’s a handy CSS media query to target Internet Explorer 11:

    
CSS
@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) { // IE-specific styles here }

What if you wanted your main stylesheet clean of any IE related code? You can’t use the conditonal comment since Microsoft removed it. User agents can be spoofed. What do you use? Recently I was looking at the MDN for clarification on the preload attribute for the link tag. I noticed an attribute I’ve only used for loading print stylesheets. Enter the <link> tag’s media attribute. The media attribute will load any file referenced in the href attribute of the <link> tag which matches the specified media query. If we wanted to load a specific stylesheet for devices with a screen size below 600px, we would add the following snippet inside the <head> tag of the page:

    
HTML
<link href="mobile.css" rel="stylesheet" media="screen and (max-width: 600px)">

Now, we can use this discovery to load a stylesheet only for IE 11:

    
HTML
<link href="/path/to/ie.css" rel="stylesheet" media="all and (-ms-high-contrast: none), (-ms-high-contrast: active)">

That’s it! Not exactly the same as the conditional comment block; but at least you can load a separate stylesheet for IE users.