By Simon Willison

Smarter selectors

By Simon Willison

The key to writing smart CSS is mastering selectors. Although often overlooked, applying them in an intelligent way can dramatically reduce the size of your stylesheet while simultaneously keeping it more maintainable and easier to alter later on. Eric Meyer has a useful piece covering some of the aspects of selectors that are frequently misunderstood. If you feel like some revision, Russ Weakley’s Selectutorial covers the basics very nciely indeed.

  • Thanks for pointing this out. Eric Meyer’s article mentions a feature that I didn’t know (using several class names in one class attribute) that I think can be helpful.
    I also struggle frequently with shortening my CSS style sheets, because I’m never 100% sure which element inherits from what element and which definitions can be left out accordingly.

  • Thirteenva

    Great link, I also did not know you could use two class names on class attribute.

    Streamlined css is important, especially in the large web app I’m working on right now. Each module has its own CSS but i’ll still need to optimize them as much as possible to keep the overhead down.

  • Rick

    That multiple classes thing, as


    does anyone know which browsers support this?

  • Rick: all modern browsers do – IE 4+, Opera, Netscape 6+, Mozilla, Firefox, Safari… in fact I’m pretty sure even Netscape 4 does although I don’t have it to hand for testing at the moment.

  • Gabe

    However, on IE 5 Mac beware of the whitespace bug in the class attribute. Basically it treats a space as a wildcard that can match anything. So in Rick’s example, not only would IE 5 Mac match the class .subtotal, it would also match .subtotal2 or .subtotalHeading or anything else of that form. Makes for some really nasty bugs that make no sense.

Get the latest in JavaScript, once a week, for free.