CSS Specificity with Eric Meyer

ericmeyerYou’re probably familiar with the LoVe-HAte rule – that being the rule that your link states should be in the order link-visitedhover- active. Why? Specificity! Because a:link, a:hover, and so on all have the same specificity, the order they’re listed in matters. If you put a:link after all the other link states, then its colour will always win, even if the link is hovered or clicked. Knowing this, you can decide where to put :focus styles, should you be using them (and you should be). Should links’ focus styles override hover styles, or be overridden by them? Whichever you decide, knowing that conflicts will likely be decided based on the order of the link states, you can make your own determination.

Ordering attribute selectors
If you’re using attribute selectors (which are supported in all makes of browsers, including IE7 and up), you may not be aware that their specificity is counted the same as for classes. This leads to an interesting conflict: p[id=”lead”] has a lower specificity than p#lead, even though both select exactly the same element in a document. Therefore, if you happen to use both selectors in your CSS, any conflicts between the two would be won by the declarations in the p#lead rule. It also means that if you have two rules applying to the same element, one using a class and the other an attribute selector, their order can matter.

ul[id=”first-list”] {list-style-type: disc;}
ul.instructions {list-style-type: square;}

… then <ul class=”instructions” id=”first-list”>

will have square bullets, not discs.