HTML and CSS Reference
3. Sort rules with the same importance and origin by specificity of selector: more specific
selectors will override more general ones. Pseudo-elements and pseudo-classes are
counted as normal elements and classes, respectively.
4. Finally, sort by order specified: if two declarations have the same weight, origin and
specificity, the latter specified wins. Declarations in imported style sheets are considered
to be before any declarations in the style sheet itself.
Translating the Spec
While the W3C's cascading order is fairly straightforward, let's further simplify their list, trans-
lating item by item (our numbers coincide with the quoted specification):
1. Find the matching target element(s), and apply the styles.
2. The browser (or user agent) should apply its own default styles first, then apply rules
from a user-specified style sheet (if one exists), followed by author style sheets (apply-
ing !important declarations last), and finally !important rules from a user-specified
style sheet (again, if it exists).
3. Rules with more specific selectors override less specific selectors (the part about
pseudo-elements and pseudo-classes applies to Table 3-1 later in this chapter).
4. If two or more selectors match the same target element and have the exact same score,
whichever comes later in the style sheet gets the girl (or guy), and any rules within style
sheets imported into other style sheets are sorted earlier.
@IMPORT AND THE CASCADE
The @import rule exists to allow users to import style sheets from within other style sheets. Although this
rule is widely used to hide style sheets from older browsers (see Chapter 6), it can also be used to help man-
age multiple CSS files (as noted in Chapter 5). Because the Cascade assigns a lower importance to rules
within imported style sheets, it's worth understanding how it will affect your styles should you use @import
in your projects.
For example, let's say you have a default style sheet ( base.css ) that imports a second style sheet for
your typography. The following @import statement would be located at the top of your default style sheet,
prior to any rules:
If within typography.css you have a rule setting the font-size for all h3 elements to 12px , but if
somewhere in base.css you happen to have a rule targeting h3 s and assigning them font-size:14px;
the latter rule will override the rule set in your imported typography style sheet.
The cascade assigns importance to rules within imported style sheets based on the order they are
imported (style sheets imported earlier have lower importance)—something to be aware of if you import
multiple style sheets (or if you import style sheets recursively).