I was wondering what an efficient algorithm would be in the following scenario:
Given a parsed set of css rules, eg.
<p class="pStyle anotherPStyle">hello</p>
p, pStyle and anotherPStyle
That is determined by specificity. In this case, since they are both equally specific, the declaration that comes last in the file, wins.
Specificity is calculated by ranking the different parts of the selector.
Ranked from most specific to least:
rank n > rank n+1, regardless of how many points each rank has.
ul#nav li.active a
The points are:
Therefore, each property in that selector has a specificity value of
[0,0,1,1,3] (We'll get to that extra zero in a minute). That value is more specific than any selector, as long as it might be, without an ID, for example.
More important notes:
- The universal selector
(*)has no specificity value (0,0,0,0) Pseudo-elements (e.g.
pseudo-class brethren which get
- The pseudo-class
:not()adds no specificity by itself, only what's inside it's parentheses.
!importantdirective can be applied on a single declaration, and adds a point to a "0th" rank, which is more specific than anything
else. So in the example above, adding
!importanton any rule will
bump the specificity value for that rule only to
granting it an instant win over any other rules without
See this great article on the subject
The way the browser does it, is to go over the selector from right to left, and filtering elements out of the DOM as they go.
Going back to the previous example:
ul#nav li.active a
The browser does the following:
lielement with an
.activeclass (this is through the descendant combinator:
ulwith an ID of
#nav(again, the descendant combinator is used).
If all these conditions are met for a certain element, then the styles are applied to it.
You can read it:
with an ancestor with a class of
.active, which is also a
which in turn has an ancestor with an ID of
#nav, which is also a
You'll need to have a fully function and complete DOM tree to be able to successfully determine which element has what CSS styles.