0
0
CSSmarkup~10 mins

First-child and last-child in CSS - Browser Rendering Trace

Choose your learning style9 modes available
Render Flow - First-child and last-child
[Parse CSS selectors] -> [Match :first-child and :last-child] -> [Apply styles to matched elements] -> [Recalculate layout] -> [Paint changes] -> [Composite layers]
The browser reads CSS selectors, finds elements that are the first or last child of their parent, applies the styles, recalculates layout, paints the changes, and composites the final view.
Render Steps - 3 Steps
Code Added:li:first-child { color: red; font-weight: bold; }
Before
[ul]
  [li] Item 1
  [li] Item 2
  [li] Item 3
After
[ul]
  [li] Item 1
  [li] Item 2
  [li] Item 3
The first <li> is colored red and made bold because it matches :first-child.
🔧 Browser Action:Matches :first-child selector, applies styles, triggers repaint.
Code Sample
The first list item is styled red and bold, the last list item is styled blue and italic, and the middle item remains default.
CSS
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
CSS
li:first-child {
  color: red;
  font-weight: bold;
}
li:last-child {
  color: blue;
  font-style: italic;
}
Render Quiz - 3 Questions
Test your understanding
After applying step 1, which list item is styled red and bold?
AThe last <li> element
BThe first <li> element
CAll <li> elements
DThe middle <li> element
Common Confusions - 2 Topics
Why doesn't :first-child style apply if my element is not the very first child?
The :first-child selector only matches an element if it is literally the first child of its parent. If there is another element or text node before it, it won't match. See render_step 1 where only the first <li> is styled.
💡 Only the very first child element gets :first-child styles.
Why does :last-child not style the element if I expect it to?
The :last-child selector matches only the last child element of the parent. If there are other siblings after it, it won't match. In render_step 2, only the last <li> is styled blue and italic.
💡 Only the very last child element gets :last-child styles.
Property Reference
SelectorWhat It MatchesVisual EffectCommon Use
:first-childElement that is the first child of its parentApplies styles only to the first child elementHighlight first item in a list or container
:last-childElement that is the last child of its parentApplies styles only to the last child elementHighlight last item in a list or container
Concept Snapshot
:first-child and :last-child select elements that are the first or last child of their parent. :first-child styles only the very first child element. :last-child styles only the very last child element. Commonly used to highlight first or last items in lists or containers. If an element is not literally first or last, these selectors won't match.