How to Use :first-child in CSS for Targeting First Elements
Use the
:first-child pseudo-class in CSS to select and style the first child element of its parent. It matches only if the element is the very first child inside its parent container.Syntax
The :first-child selector targets an element only if it is the first child of its parent. It is written by placing :first-child after the element or selector.
- element:first-child — selects the element if it is the first child.
- selector:first-child — selects any element matching the selector if it is the first child.
css
element:first-child {
/* styles here */
}Example
This example shows how to color the first li item in a list red using :first-child. 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 matches if the element is the very first child of its parent, not just the first of its type.
For example, if a p is the second child but the first p inside a container, p:first-child will not select it.
css
/* Wrong: This will NOT select the first <p> if it is not the first child */ p:first-child { color: blue; } /* Right: Use :first-of-type to select the first <p> regardless of position */ p:first-of-type { color: blue; }
Quick Reference
| Selector | Description |
|---|---|
| :first-child | Selects an element if it is the first child of its parent. |
| :first-of-type | Selects the first element of its type among siblings. |
| element:first-child | Selects the element if it is the first child. |
| selector:first-child | Selects any matching element if it is the first child. |
Key Takeaways
Use :first-child to style only the very first child element inside a parent.
:first-child matches the element only if it is the first child, not just the first of its type.
To select the first element of a type regardless of position, use :first-of-type instead.
Always check the HTML structure to ensure the element is actually the first child.
Combine :first-child with element selectors for precise styling.