HTML and CSS Reference
In-Depth Information
<div id="main" class="container"></div>
In this case, it might seem that the second rule set, which uses two type selectors, a class
selector and a descendant selector all in one, would have precedence over the first rule set,
which only uses the ID selector. But this isn't the case. The color value on the container ele-
ment would become green because the ID selector (used in the first example) has very high
specificity and thus takes precedence over the second rule set.
It should be noted here that when we refer to the overriding of selectors and selectors taking
precedence, we're assuming that the same styles are defined on these different rule sets. So,
for example, in the previous code block, if the #main rule set defined color and the body
div.container selector defined a different property, then they would both apply, because
there'd be nothing being overridden. To recap, then: specificity does not affect all styles, but
only the styles that are duplicated across multiple selectors.
This use of the ID selector—and its strong override abilities—clearly illustrates why it's im-
portant to avoid using it, wherever possible. Traditionally, CSS developers have encouraged
the ID selector's use for unique elements, and, according to standards, it's a perfectly valid
CSS selector. But please keep in mind that overusing it may cause all sorts of problems in the
long run.
Inordertoavoidbeingtrippedupbyspecificity,usetheclassselectorwidelyandlearnwhat's
referred to as "Object Oriented CSS" or "modular CSS". [1]
Note: Selective Treatment
ThesuggestiontoavoidIDselectorsonlyappliestoIDsinCSS,notinHTML.
ID attributes are absolutely necessary for local, or same-page, links and can
be very useful when attempting to target elements using JavaScript.
Other selectors will also add certain levels of specificity, but not so much that they'll cause
problems. If, for example, you have to target something with a pseudo-class or child selector,
that's fine. Use those selectors whenever you find them to be practical.
There are a number of detailed articles online explaining cascade and specificity. These in-
cludeaserieson SitePoint'sCSSReference, whicharehighlyrecommendonceyou'veagood
grasp of some of the basics introduced in this topic.
 
 
Search WWH ::




Custom Search