from a css stylesheet, it is possible that several rule sets apply to a given element (say a

<p class="pStyle anotherPStyle">hello</p>

in my document).

I need to determine what rules in the stylesheet apply to a given element firstly (so here that is

p, pStyle and anotherPStyle

), and then create a Comparator that is able to sort the applicable rules by specificity (from most-specific to most-general). NOTE: I already have designed an algorithm to apply the rules once sorted so you needn't solve that problem efficiently.

I've been toying with several ideas, namely one that involves determining the level in the DOM tree that a given rule is specific to....Though I'm not sure if this is the correct way to go?

How does the browser engine do this efficiently? I'm looking to replicate it in Java, but am comfortable with many other languages so any code you can offer is most appreciated.

That is determined by specificity. In this case, since they are both equally specific, the declaration that comes last in the file, wins.

Specificity Calculation

Specificity is calculated by ranking the different parts of the selector.

Ranked from most specific to least:

Style attribute - If the rule is found in a style attribute, this rank gets 1.

ID - For each ID found in the selector, this rank gets an additional 1.

Classes, Pseudo-Classes, Attribute selectors - For each one found in the selector, this rank gets an additional 1.

Elements - For each element found in the selector, this rank gets an additional 1.

Where rank n > rank n+1, regardless of how many points each rank has.

Example

ul#nav li.active a

The points are:

0 - Not a style attribute.

1 - 1 ID found.

1 - 1 Classname found.

3 - 3 Elements found.

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.

Comparison algorithm:

Go from left to right on the ranks.

Compare the ranks on both selectors.

The rank with the higher amount of point, wins.

If the ranks are equal, continue right to the next (less specific) rank.

If all ranks are equal, the one which comes later in the CSS document, wins.

More important notes:

The universal selector (*) has no specificity value (0,0,0,0) Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their
pseudo-class brethren which get 0,0,1,0

The pseudo-class :not() adds no specificity by itself, only what's inside it's parentheses.

The !important directive 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 !important on any rule will
bump the specificity value for that rule only to [1,0,1,1,2],
granting it an instant win over any other rules without !important.