Categories
Code

Conditional IE classes

The HTML5 Boilerplate popularised the html tag conditional classes pattern. This pattern is usually some variation of:

<!DOCTYPE html>
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en"> <!--<![endif]-->
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge" /> 

This pattern allows the developer to target IE fixes using code similar to:

.rgba-bg {
  background-color: rgba(255,0,0,0.2);
}
  .ie6 .rgba-bg,
  .ie6 .rgba-bg,
  .ie6 .rgba-bg {
    background-image: url('i/rgba/red-02.png');
  }

It also puts IE8 into compatibility mode, effectively adding another browser one needs to test against. This was included as one of the reasons the HTML5 Boilerplate recently removed it.

Avoiding this is simple, just put the conditional classes on the body tag:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
 <!-- ... -->
</head>
<!--[if lte IE 8 ]><body class="lte-ie8"> <![endif]-->
<!--[if IE 9 ]> <body class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <body> <!--<![endif]-->

I’ve dropped classes specifically targeting IE6 and 7 long ago for two reasons

  • the star and underscore CSS hacks still work if you have to support these browsers, and,
  • why would you?

The code above gives you a safe hack for all version of IE supporting conditional comments, without having to worry about compatibility mode.

As an aside, this fallback for rgba backgrounds is much better than the one above:

.rgba-bg {
  background-image: url('i/rgba/red-02.png');
  background-image: none,none;
  background-color: rgba(255,0,0,0.2);
}

caniuse.com is a recipe book.

By Peter Wilson

Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development.

Peter’s a big fan of musical theatre and often encourages his industry colleagues to join him for a show or two in New York or in the West End.

Leave a Reply

Your email address will not be published. Required fields are marked *