Performance: Specificity rules
Specificity affects how quickly browsers determine which CSS rules apply, impacting style calculation and rendering speed.
Jump into concepts and practice - no test required
.active-link { color: red; }
body div#main.content > ul li.item.active a:hover { color: red; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Highly specific complex selector | Many element checks | 0 (style only) | Low | [X] Bad |
| Simple class selector | Few element checks | 0 (style only) | Low | [OK] Good |
#header is an ID selector, which beats class .menu and element div selectors.#header -> Option A# before the name, classes with ., and combinators like > properly placed.# which is invalid syntax. .container > #main .item is correctly formed..container > #main .item -> Option A.container > #main .item [OK]p { color: blue; }
.content p { color: green; }
#content p { color: red; }p is element selector (lowest), .content p has a class and element, and #content p has an ID and element. ID selector has highest specificity.#content p rule overrides others because ID selectors beat class and element selectors.h1 { color: blue; }
#title { color: red; }
.title { color: green; }<h1 class="title" id="header">Hello</h1>
id="header" and class="title". The selector #title targets an element with ID "title", which does not match.#title does not match, its rule is ignored. The class selector .title applies green, which overrides the element selector blue.#title does not match the element's ID -> Option C.btn { color: black; }
button { color: blue; }
#submit.btn { color: green; }<button id="submit" class="btn">Send</button>
.btn is class selector (specificity 0,1,0), button is element selector (0,0,1), and #submit.btn combines ID and class (1,1,0), highest specificity.#submit.btn selector wins because it has the highest specificity, so the color is green.