Role of CSS: first-child Selector

The CSS :first-child selector targets the first child element of its parent, regardless of element type. It's commonly used to apply special styling to the first item in a list or the first paragraph in a container.

Syntax

selector:first-child {
    property: value;
}

Example: Basic Usage

The following example styles every <p> element that is the first child of its parent −

<!DOCTYPE html>
<html>
<head>
<style>
    p:first-child {
        background-color: orange;
        padding: 10px;
        font-weight: bold;
    }
</style>
</head>
<body>
    <h1>Heading</h1>
    <p>This paragraph is NOT the first child (h1 is first).</p>
    <div>
        <p>This is the first child of the div - styled!</p>
        <p>This is the second paragraph - not styled.</p>
    </div>
    <section>
        <p>This is also the first child of section - styled!</p>
        <span>This span comes after the paragraph.</span>
    </section>
</body>
</html>
Only the first paragraph inside the div and the first paragraph inside the section have orange background, padding, and bold text. The paragraph directly under h1 is not styled because h1 is the first child of body.

Example: Universal First Child

You can also use :first-child with the universal selector to target any first child element −

<!DOCTYPE html>
<html>
<head>
<style>
    div :first-child {
        color: blue;
        text-decoration: underline;
    }
</style>
</head>
<body>
    <div>
        <h2>First child - styled!</h2>
        <p>Second child - not styled.</p>
        <ul>
            <li>First li - styled as first child of ul!</li>
            <li>Second li - not styled.</li>
        </ul>
    </div>
</body>
</html>
The h2 element and the first li element appear in blue with underlines, as they are the first children of their respective parent elements.

Conclusion

The :first-child selector is perfect for styling the first element within containers. Remember it selects based on position, not element type, making it versatile for various layout designs.

Updated on: 2026-03-15T12:19:07+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements