Specificity etcetera

Only doing css for my own stuff, I’ve never fully grasped just specificity works (and maybe never will) - instead using kludges to get things to behave.

One such instance is with my ul lists…

My primary nav is a ul list, with all items in a line. I usually write the css as ‘#primary-nav ul’ to avoid it affecting ul lists elsewhere on the page.

But sometimes the ul style for those lists then also affects the primary nav ul, and so to avoid this I have to add id/class to the ul.

Clearly this isn’t good, and I’m keen to understand things better so I can properly set up the primary nav ul and not have it affected by other ul style further-on in the css.

Ok, here goes…!

The first thing is to be clear about specificity and inheritance. Lots of properties are inherited, but they are always overridden by styles targeting child elements, no matter how specific.

If you have two conflicting rules that apply to the same element, there’s a simple process to see which one is applied - in order:

  1. If one of them is called using inline styles and the other through an embedded or external stylesheet, the inline one wins.
  2. If one of them is marked as !important and the other isn’t, the !important one wins.
  3. If one of them has more IDs in its selector chain than the other then it wins *.
  4. If one of them has more classed in its selector chain than the other then it wins **.
  5. If one of them has more elements in its selector chain than the other then it wins.
  6. Whichever one appears last (taking all linked and imported stylesheets as being inserted at the href) wins.
  • It doesn’t matter what elements the IDs are applied to.
    #page div.container p and body.page div #highlight have the same specificity

** Pseudo-classes such as :link or :first-child carry the same weight as regular classes.

Thanks. I’ll study that and hopefully not have to post more dumb questions.

The sitepoint reference has a nice section on specificity (I wrote half of them :)) and is worth a read as it does explain thoroughly the concepts of cascade, specificity and inheritance.

Thanks. Now bookmarked, I shall study it.