Performance: First-child and last-child
This affects the browser's style calculation and layout performance when selecting elements based on their position in the DOM.
Jump into concepts and practice - no test required
li { color: black; }
li:first-child { color: red; }
li:last-child { color: blue; }li { color: black; }
li:first-child { color: red; }
li:last-child { color: blue; }
li:nth-child(n) { color: black; }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| :first-child and :last-child on small lists | Minimal DOM traversal | 0 | Low | [OK] Good |
| :first-child and :last-child on large lists repeatedly | High DOM traversal per element | 0 | Medium | [!] OK |
| Using JavaScript to add classes instead | Extra DOM manipulation | 1 | Low | [!] OK |
| Avoiding positional selectors entirely | Minimal DOM traversal | 0 | Low | [OK] Good |
:first-child do?:first-child selector targets only the very first child element within a parent container.:last-child targets the last child, others do not match the description.<ul> list?<li> inside a <ul>, so the selector must target li elements that are last children.ul > li:last-child correctly selects the last li directly inside ul. Other options either select the wrong element or use incorrect syntax.<ul> <li>Apple</li> <li>Banana</li> <li>Cherry</li> </ul>
li:first-child { color: blue; }
li:last-child { color: green; }li:first-child styles the first li (Apple), li:last-child styles the last li (Cherry).li, so it is neither first nor last child, so no color styles apply.<section> green and blue respectively:section p:first-child { color: green; }
section p:last-child { color: blue; }p is first or last childp, then p is not first or last child, so styles won't apply.p elements are not the first or last child of section. -> Option D<li> elements inside every <ul> differently, but only if the <li> is also the first or last child of its parent. Which CSS selectors correctly achieve this?li elements that are the first or last child of their ul parent.ul > li:first-child and ul > li:last-child select li elements that are direct children and first or last child respectively. This matches the requirement exactly.ul. ul li:first-of-type { font-weight: bold; } and ul li:last-of-type { font-style: italic; } uses :first-of-type which selects first li regardless of position among siblings.