Performance: Nth-child selector
This affects CSS selector matching speed and can impact rendering performance when used on large DOM trees.
Jump into concepts and practice - no test required
ul li { background-color: white; } ul li:nth-child(3n) { background-color: lightblue; }ul li:nth-child(3n) { background-color: lightblue; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| ul li:nth-child(3n) | Checks every li element | 0 | Low | [OK] |
| ul li.simple-class | Checks only elements with class | 0 | Low | [OK] Good |
li:nth-child(3) select?nth-child selectornth-child(n) selector targets the element that is the nth child of its parent, counting all types of children.li:nth-child(3)li element only if it is the third child of its parent. It does not select the third li if other elements come before it.li:nth-child(3) = third child of any type [OK]div inside a container using :nth-child?even keyword meaningeven in :nth-child(even) selects all even-numbered children (2nd, 4th, 6th, etc.).div elementsdiv:nth-child(even) selects every div that is an even child of its parent.<ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul>
li:nth-child(2n) { color: red; }2n in nth-child2n selects every even child: 2nd, 4th, 6th, etc.p element blue?p:nth-child(3n+1) {
color: blue;
}3n+13n+1 selects children at positions 1, 4, 7, 10, ...3n, not 3n+1.li elements inside a ul without styling the 6th or others. Which CSS selector achieves this?li elements, excluding the 6th or any others.li except the 6th, but also includes 8th, 10th, etc. li:nth-child(2n) selects all even li elements (2nd, 4th, 6th, ...). li:nth-child(2n+2) selects 2nd, 4th, 6th, ... as well. li:nth-child(2), li:nth-child(4) explicitly selects only the 2nd and 4th li elements.