How to Select First Child in CSS: Simple Guide
Use the
:first-child pseudo-class in CSS to select the first child element of its parent. For example, p:first-child targets any <p> element that is the first child inside its parent container.Syntax
The :first-child selector targets an element that is the first child of its parent. It is written by placing :first-child after the element selector.
- element:first-child: Selects the element only if it is the first child of its parent.
css
element:first-child {
/* CSS properties here */
}Example
This example shows how to color the first li item in a list red. Only the very first list item inside the ul will be red.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>First Child Example</title> <style> ul li:first-child { color: red; font-weight: bold; } </style> </head> <body> <ul> <li>First item</li> <li>Second item</li> <li>Third item</li> </ul> </body> </html>
Output
A bulleted list with three items: 'First item' is red and bold, 'Second item' and 'Third item' are normal black text.
Common Pitfalls
One common mistake is expecting :first-child to select the first element of a type regardless of its position. It only selects an element if it is literally the first child of its parent.
For example, if a p is not the first child but the second or later, p:first-child will not select it.
css
/* Wrong: This will not select the second <p> even if it is the first <p> */ div p:first-child { color: blue; } /* Right: Use :first-of-type to select the first <p> regardless of position */ div p:first-of-type { color: blue; }
Quick Reference
:first-childselects an element only if it is the first child of its parent.:first-of-typeselects the first element of its type inside the parent, regardless of other siblings.- Use
:first-childfor strict first-child selection, and:first-of-typewhen you want the first element of a specific type.
Key Takeaways
Use
:first-child to select an element only if it is the first child of its parent.The element must be literally the first child; otherwise,
:first-child won't match it.For selecting the first element of a type regardless of position, use
:first-of-type instead.Always test your selectors in the browser to confirm they target the intended elements.
Combine
:first-child with element selectors for precise styling.