0
0
CSSmarkup~8 mins

First-child and last-child in CSS - Performance & Optimization

Choose your learning style9 modes available
Performance: First-child and last-child
LOW IMPACT
This affects the browser's style calculation and layout performance when selecting elements based on their position in the DOM.
Styling only the first and last items in a list
CSS
li { color: black; }
li:first-child { color: red; }
li:last-child { color: blue; }
Only uses necessary positional selectors without redundant rules, minimizing style checks.
📈 Performance Gainsingle style calculation pass with minimal overhead
Styling only the first and last items in a list
CSS
li { color: black; }
li:first-child { color: red; }
li:last-child { color: blue; }
li:nth-child(n) { color: black; }
Using multiple complex positional selectors on many list items forces the browser to check each element's position repeatedly.
📉 Performance Costtriggers style recalculation for each list item, increasing with list size
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
:first-child and :last-child on small listsMinimal DOM traversal0Low[OK] Good
:first-child and :last-child on large lists repeatedlyHigh DOM traversal per element0Medium[!] OK
Using JavaScript to add classes insteadExtra DOM manipulation1Low[!] OK
Avoiding positional selectors entirelyMinimal DOM traversal0Low[OK] Good
Rendering Pipeline
The browser matches :first-child and :last-child selectors during the Style Calculation stage by checking element positions in the DOM tree. This can cause extra work if many elements are involved.
Style Calculation
Layout
⚠️ BottleneckStyle Calculation due to positional checks
Optimization Tips
1Use :first-child and :last-child sparingly on large DOM trees.
2Combine positional selectors with classes to reduce complexity.
3Avoid redundant or overlapping positional selectors to minimize style recalculation.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance cost of using :first-child and :last-child selectors on a large list?
AIncreases JavaScript execution time
BTriggers multiple reflows and repaints
CExtra style calculation time due to checking each element's position
DBlocks network requests
DevTools: Performance
How to check: Record a performance profile while loading or interacting with the page. Look for long Style Calculation times.
What to look for: High time spent in 'Recalculate Style' indicates costly selector matching like :first-child or :last-child on large DOMs.