The Specificity Duel
Several CSS rules fight over the same element. Compute every selector's specificity and name the rule the browser really applies.
Statement
Story
A teammate's stylesheet is fighting itself: several rules target the same <button> and set the same color, yet the page keeps showing the wrong one. Before anyone reaches for !important, you write a tiny tool that says which rule wins and why.
The rules of the duel
Every selector in the input matches the same element and sets the same property. No rule uses !important and there are no inline styles. The specificity of a selector is a triple (a, b, c):
- a: the number of ID selectors (
#nav) - b: the number of class selectors (
.btn), attribute selectors ([type="text"]) and pseudo-classes (:hover,:nth-child(2n+1)) - c: the number of type selectors (
div) and pseudo-elements (::before)
The universal selector * and the combinators (space, >, +, ~) add nothing. Every occurrence counts, so .a.a is (0, 2, 0). Triples are compared left to right: (1, 0, 0) beats (0, 99, 0), the numbers never carry over into the next position. If two rules have the same specificity, the one that appears later in the stylesheet wins.
Input
The first line holds N (1 ≤ N ≤ 100). The next N lines are the selectors in source order, one per line. Each is a single complex selector (no commas) with combinators surrounded by single spaces. Attribute values never contain spaces or ]. Pseudo-classes are either plain (:hover) or take a plain argument (:nth-child(2n+1), :lang(en)); pseudo-elements always use the double-colon form (::before). :not(), :is() and :where() are not used.
Output
One line: <index> <a>,<b>,<c>, the 1-based index of the winning rule and its specificity.
Example
Input:
3
#nav a
.menu li a
ul li a:hover
Output:
1 1,0,1
#nav a is (1, 0, 1), while the other two have no ID at all: (0, 1, 2) and (0, 1, 3).
Sample input
3 #nav a .menu li a ul li a:hover
Hints
Stuck? Hints are optional, and each one lowers the points you earn for solving this challenge.
- Hint 1Costs 5 points
- Hint 2Costs 5 points
Reveal the previous hint first
- Hint 3Costs 8 points
Reveal the previous hint first
Lessons that teach this
Stuck on the ideas rather than the puzzle? These lessons cover what you need.