Performance: Debugging specificity issues
This affects how quickly styles are applied and can impact rendering speed if many conflicting rules cause repeated style recalculations.
Jump into concepts and practice - no test required
.item-active-link { color: red; font-weight: bold; }
div.content > ul li.item.active a:hover { color: red; font-weight: bold; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Complex selector with many combinators | High (many nodes matched repeatedly) | Multiple on state changes | High due to frequent recalculations | [X] Bad |
| Simple class selector | Low (direct match) | Single or none | Low, minimal recalculations | [OK] Good |
#header is an ID selector, which beats class .menu and element div.#header -> Option A.btn.primary targets elements with both classes, increasing specificity..btn.primary { color: blue; } combines two classes without space, increasing specificity. .btn .primary { color: blue; } has a space, meaning descendant selector, which is less specific..btn.primary { color: blue; } -> Option D<p class='text'> element display?p { color: red; }
.text { color: green; }
#main p { color: blue; }id='main'.p, .text, and #main p selectors.p has lowest specificity, .text is higher, and #main p has highest specificity because of the ID..btn { background: yellow; }
#submit { background: green; }
.btn.primary { background: red; }class='btn primary' and id='submit'. Which background color will it show and why?#submit is an ID selector, highest specificity. .btn.primary combines two classes, less specific than ID.#submit overrides class selectors, so background is green..card { border: 1px solid black; } but cannot change their CSS file. Which selector below will reliably override their border style without using !important?.card is a single class selector.#main .card combines an ID and a class, which has higher specificity than a single class.div.card combines element and class, less specific than ID. .card.primary combines two classes, still less than ID. .card, .primary is two separate selectors, no increased specificity.#main .card -> Option B