CSS Specificity Headaches

CSS isn’t the most friendly of languages: globally operating, very leaky, dependent on location, hard to encapsulate based on inheritance, but none of that even comes close to the horrors of CSS specificity.

No matter how well considered your naming, regardless of how perfect your source order and cascade are managed, and how well you’ve scoped your rulesets, just one overly-specific selector can undo everything. It is a gigantic curveball, and undermines CSS’ very nature of the cascade, inheritance, and source order.

The problem with specificity is that it sets precedents and trumps that cannot simply be undone. If we take a real example that I was responsible for some years ago:

#content table {}

Not only does this exhibit poor selector intent—I didn’t actually want every table in the#content area, I wanted a specific type of table that just happened to live there—it is a hugely over-specific selector. This became apparent a number of weeks later, when I needed a second type of table:

#content table {}

 * Uh oh! My styles get overwritten by `#content table {}`.
.my-new-table {}

The first selector was trumping the specificity of the one defined after it, working against CSS’ source-order based application of styles. In order to remedy this, I had two main options. I could:

  1. refactor my CSS and HTML to remove that ID;
  2. write a more specific selector to override it.

Unfortunately, refactoring would have taken a long time; it was a mature product and the knock-on effects of removing this ID would have been a more substantial business cost than the second option: (just write a more specific selector)

#content table {}

#content .my-new-table {}

Now I have a selector that is even more specific still! And if I ever want to override this one, I will need another selector of at least the same specificity defined after it. I’ve started on a downward spiral.

Specificity can, among other things,

  • limit your ability to extend and manipulate a codebase;
  • interrupt and undo CSS’ cascading, inheriting nature;
  • cause avoidable verbosity in your project;
  • prevent things from working as expected when moved into different environments;
  • lead to serious developer frustration.

All of these issues are greatly magnified when working on a larger project with a number of developers contributing code.

Feel free to share this to anyone else looking for CSS specificity information.

If you want to view all of our WTG guides regarding CSS go here.

references: CSS guidelines, developer.mozilla.org

We will be happy to hear your thoughts

      Leave a Comment

      Web Training Guides
      Compare items
      • Total (0)