I’m working on converting a website template to a WordPress theme and discovered very interesting.  Most people know that each browser interprets HTML and CSS differently, with Microsoft’s Internet Explorer (prior to IE8) appearing to be quite different than other browsers, such as Mozilla Firefox and Google Chrome.  Today I discovered a specific difference in how IE interprets id and class differently than Firefox and Chrome.  To IE 7, id and class appear to be treated equivalently, with neither having priority over the other.  Firefox, Chrome, and IE8, however, give a higher precedence to id.

Here’s an example:

<style>
  #selector1 { color: red; }
  .selector2 { color: green; }
</style>

<div id=”selector1”>
  <div class=”selector2”>
    Some text
  </div>
</div>

In the above example, the value specified for color on selector1 (red) will be used when displaying the page in Firefox, Chrome, or IE8.  When displaying on IE7, however, the value specified for color on selector2 (green) is used.  Therefore, the conclusion that can be drawn is that id selectors take precedence over class selectors.

Doing a little research, I found the W3C candidate documentation on selectors, which is what identifiers are called in a style sheet.  The interesting chapters are Selectors (chapter 5) and Assigning property values, Cascading, and Inheritance (chapter 6), although even after reading those chapters it still wasn’t clear what the correct priority should be.

To get around this implicit priority, you can use the !important keyword:

<style>
  #selector1 { color: red; }
  .selector2 { color: green !important; }
</style>