HTML and CSS Reference
In-Depth Information
Combinators, by comparison, have no specificity at all—not even zero specificity.
Thus, they have no impact on a selector's overall specificity.
ID and Attribute Selector Specificity
It's important to note the difference in specificity between an ID selector and an at-
tribute selector that targets an id attribute. Returning to the third pair of rules in the
example code, we find:
html > body table tr[id="totals"] td ul > li {color: maroon;} /* 0,0,1,7 */
li#answer {color: navy;} /* 0,1,0,1 (wins) */
The ID selector ( #answer ) in the second rule contributes 0,1,0,0 to the overall specificity
of the selector. In the first rule, however, the attribute selector ( [id="totals"] ) con-
tributes 0,0,1,0 to the overall specificity. Thus, given the following rules, the element
with an id of meadow will be green:
#meadow {color: green;} /* 0,1,0,0 */
*[id="meadow"] {color: red;} /* 0,0,1,0 */
Inline Style Specificity
So far, we've only seen specificities that begin with a zero, so you may be wondering
why it's there at all. As it happens, that first zero is reserved for inline style declarations,
which trump any other declaration's specificity. Consider the following rule and
markup fragment:
h1 {color: red;}
<h1 style="color: green;">The Meadow Party</h1>
Given that the rule is applied to the h1 element, you would still probably expect the
text of the h1 to be green. This is what happens as of CSS2.1, and it happens because
every inline declaration has a specificity of 1,0,0,0 .
This means that even elements with id attributes that match a rule will obey the inline
style declaration. Let's modify the previous example to include an id :
h1#meadow {color: red;}
<h1 id="meadow" style="color: green;">The Meadow Party</h1>
Thanks to the inline declaration's specificity, the text of the h1 element will still be green.
The primacy of inline style declarations was introduced in CSS2.1, and
it exists to capture the state of web browser behavior at the time CSS2.1
was written. In CSS2, the specificity of an inline style declaration was
1,0,0 (CSS2 specificities had three values, not four). In other words, it
had the same specificity as an ID selector, which could have easily over-
ridden inline styles.
Search WWH ::




Custom Search