Usage of :first-child pseudo-class in CSS

The CSS :first-child pseudo-class is used to select and style an element that is the first child of its parent element. This selector only targets the very first child element, regardless of its type.

Syntax

selector:first-child {
    property: value;
}

Example: Basic Usage

The following example demonstrates how :first-child selects the first paragraph inside a div element −

<!DOCTYPE html>
<html>
<head>
<style>
    div > p:first-child {
        text-indent: 25px;
        color: blue;
        font-weight: bold;
    }
</style>
</head>
<body>
    <div>
        <p>First paragraph in div. This paragraph will be indented and styled.</p>
        <p>Second paragraph in div. This paragraph will not be affected.</p>
    </div>
    
    <p>Paragraph outside div - not affected.</p>
    
    <div>
        <h3>Heading comes first</h3>
        <p>This paragraph is not the first child, so it won't be styled.</p>
    </div>
</body>
</html>
The first paragraph in the first div appears indented (25px), blue, and bold. The second paragraph and the paragraph in the second div (after the heading) remain unstyled with default formatting.

Key Points

  • The :first-child selector only matches the very first child element of a parent
  • If the first child is not the target element type, the selector won't match anything
  • It's commonly used for removing margins from the first element or adding special styling

Conclusion

The :first-child pseudo-class is essential for targeting the first child element within a container. Remember that it selects based on position, not element type, so ensure the first child matches your selector.

Updated on: 2026-03-15T11:27:29+05:30

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements