DEV Community

Youn
Youn

Posted on

CSS :first-child Pseudo-Class Selector

😄 This post is based on the content from coding.courses.

Definition and Usage

The :first-child pseudo-class selector selects the element that is the first child of its parent.
The :first-child pseudo-class selector is the same as the :nth-child(1).

Basic Example

<!-- HTML -->
<ol>
    <li>li</li>
    <li>li</li>
    <li>li</li>
    <li>li</li>
</ol>

/* CSS */
li:first-child {
    background-color: yellowgreen;
}
Enter fullscreen mode Exit fullscreen mode

Syntax

:first-child {
    /* ... */
}
Enter fullscreen mode Exit fullscreen mode

Examples

# Styling the First Heading Element

<!-- HTML -->
<article>
    <h2>Heading Element</h2>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</article>

/* CSS */
article h2:first-child {
    background-color: yellowgreen;
}
Enter fullscreen mode Exit fullscreen mode

# Styling Nested Elements

<!-- HTML -->
<article>
    <div>This 'div' is the first one.</div>
    <div>This <span>nested 'span' is the first one.</span>!</div>
    <div>
        This <em>nested 'em' is the first one.</em>, but this <em>nested 'em' is the last one.</em>!
    </div>
    <div>This <span>nested 'span' is styled.</span>!</div>
    <p>This 'p' is not the first child.</p>
    <div>This 'div' is the last one.</div>
</article>

/* CSS */
article *:first-child {
    background-color: yellowgreen;
}
Enter fullscreen mode Exit fullscreen mode

References

CSS :first-child Pseudo-Class Selector – codingCourses

The :first-child pseudo-class selects the element that is the first child of its parent. It works the same as the :nth-child(1).

favicon coding.courses

Top comments (0)