Skip to main content

What does :first-child do?

:first-child is a pseudo-class that selects the element that is the first child of its parent. It only triggers if the element genuinely comes first inside the container, among all siblings at the same level.


Example

html
<ul> <li>First</li> <li>Second</li> </ul>
css
li:first-child { color: red; }

In this example, only the first <li> becomes red, because it is the first child element inside ul.


When :first-child will NOT work

If li is not first in the list:

html
<ul> <span></span> <li>Item</li> </ul>

Then li:first-child will not apply, because the first child is span.


Summary

:first-child selects only those elements that sit in the first position inside their parent. It depends on the HTML structure and does not look at the tag type, only the position in the tree matters.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.