CSS 2.1 is the new hotness

Forget for a moment about border-radius, box-shadow, and all the other funky CSS3 properties you can use in modern browsers. The (slow) death of IE6 is causing a quiet revolution at the other end of the browser spectrum.

IE6 does not natively understand many significant features of CSS2.1, such as the child (>), adjacent sibling (+), and attribute ([attr]) selectors. Because of this, many web developers (myself included) often ignore them, and work with a more highly-compatible subset of CSS. But if you have the luxury of ignoring IE6–and unfortunately it is still a luxury–then all of these cool features (and more!) suddenly come into play, and they can make your code a lot cleaner.

My favourite illustration of CSS2.1 hotness is nested modules. Here’s some typical HTML:

<div class="mod mod-blog">
  <div class="hd">My awesome blog</div>
    <div class="bd">
    ...
      <div class="mod mod-blogentry">
      <div class="hd">My awesome breakfast</div>
      <div class="bd">
        ...
      </div>
      <div class="ft"></div>
    </div>
  ...
  </div>
  <div class="ft"></div>
</div>

If you use a descendant selector to style the .hd of the outer module, you have to be careful to override any styles for the .hd of the inner module, otherwise the outer styles will apply to it, too:

.mod-blog .hd {
  font-size:167%;
  font-weight:bold;
}

.mod-blogentry .hd {
  font-size:100%;
  font-weight:normal;
}

Alternatively, you end up decorating the .hd element with additional classnames so that you can target the elements more specifically in your CSS (e.g. <div class=".hd .hd-blog">).

By using child a child selector, you can be much more specific in which elements you target. In this example, you can ensure that the “big and bold” style only gets applied to the header of the outer module by using the child selector:

.mod-blog > .hd {
  font-size:167%;
  font-weight:bold;
}

And boom, your code is a lot cleaner, and your modules can be coded in a much more modular style–without having to worry quite so much about nesting issues and inherited rules.

Of course, even if you do have to support IE6, there is nothing to stop you from using these selectors anyway. You can use a polyfill like Selectivizr to implement the missing support in IE, or you can provide IE6-specific overrides in a separate stylesheet, like so:

.ie6 .mod-blogentry .hd {
  font-size:100%;
  font-weight:normal;
}

I don’t recommend doing this, though, because IE6 is already the slowest mainstream browser on the block. Adding additional cruft is just going to make it even slower, and give your site’s visitors an even worse experience than they already have.

But seriously: if you’ve been drooling over rounded corners and gradients without background images, you owe it to yourself to remind yourself of these older features as well. You’ll be very pleasantly surprised by what you can do with them.

Further reading