Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Understanding selectors, specificity, and cascading CHAPTER 4 161


The author of the page can provide normal style declarations that override the user’s
defined styles, based on the evaluation order. The user can have the final word by overriding
the author’s declarations by using the “!important” modifier. This is probably the best imple-
mentation of the “!important” modifier.

Quick check
■■What is the order of precedence for calculating the effective style of an element?

Quick check answer
■■(1) Important, (2) Specificity, (3) Textual Order

Using specificity


Probably the most confusing aspect of determining the effective style of an element is deter-
mining the victor of conflicting styles when specificity is different among them. The rule with
the most specific selector will prevail, but how do you determine which rule is most specific?
To calculate the selector’s specificity, start by recording three values, known as a, b, and c,
as follows.
■■a Record the number of id attributes in the selector.
■■b Record the quantity of class selectors, attributes selectors, and pseudo classes.
■■c Record the quantity of element names in the selector.
Although pseudo classes are counted, pseudo elements are not counted in the specific-
ity calculation. In addition, if you use the negation pseudo class, the selectors within it are
counted, but the negation pseudo class is not counted. Last, the universal selector (*) is never
included in calculations.
After recording the values of a, b, and c, concatenate the three numbers to form a specific-
ity value so that a has the highest value, then b, and c has the lowest value. Figure 4-7 dem-
onstrates the calculation of various selectors, from the lowest specificity value to the highest
specificity value.
Free download pdf