Exercise 1: Tag vs. Class vs. Id, in Both Source Orders — Possible Solution ==================================================================== THE TEST ------------------------------ elem =

r_tag = Rule(['p'], [Declaration('color', 'black')]) r_class = Rule(['.y'], [Declaration('color', 'blue')]) r_id = Rule(['#x'], [Declaration('color', 'red')]) sheet_a = Stylesheet([r_tag, r_class, r_id]) # id rule LAST sheet_b = Stylesheet([r_id, r_class, r_tag]) # id rule FIRST cascade(elem, sheet_a)['color'] cascade(elem, sheet_b)['color'] RESULT ------------------------------ sheet_a -> 'red' sheet_b -> 'red' Both stylesheets produce the exact same winner, regardless of where the id rule sits in source order. WHY SOURCE ORDER NEVER GETS A CHANCE TO MATTER HERE ------------------------------ cascade() sorts every matching rule by the key `(specificity, order)` -- specificity FIRST, source order only as a secondary key. The three rules here have genuinely different specificities: specificity('p') -> (0, 0, 1) specificity('.y') -> (0, 1, 0) specificity('#x') -> (1, 0, 0) Comparing tuples lexicographically, (1,0,0) is strictly greater than both of the others, in EITHER stylesheet -- the id rule's own specificity tuple has a 1 in the very first position, which no combination of classes or tags can ever match or exceed (short of also using an id). Because sort() is comparing (specificity, order) pairs, and the id rule's specificity component alone already makes it the largest of the three tuples, the order component of that comparison is never even consulted to break a tie -- there simply isn't a tie to break. WHY THIS WORKS AS AN ANSWER ------------------------------ Source order is only a TIE-BREAKER, the second element of the sort key -- it only has any influence over the outcome when the first element (specificity) is identical between two competing rules. Here, all three rules have distinct, unequal specificity tuples, so the "loudest" rule (the id selector) always wins the comparison on the first key alone, and where it happened to be written in the stylesheet is irrelevant to the result. This is exactly why real CSS authors can't reliably "win" a specificity fight just by writing their rule later in the file -- source order is a fallback, not a trump card.