Open In App

What is First Child in CSS ?

Last Updated : 19 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The :first-child CSS pseudo-class is used to select and style the first child element within its parent. It specifically applies to the first child element, and no matter the type of element, it only applies the styles if the element is the very first child of its parent. This is useful when you want to apply special styling to only the first child in a group of elements.

Syntax:

:first-child {
     //property
}

Example 1: Simple Demonstration of :first-child

In this example, the :first-child selector is used to style the first <p> tag in a div element.

HTML
<!DOCTYPE html>
<html>

<head>
    <style>
        p:first-child {
            background: limegreen;
            color: white;
            font-style: italic;
            font-size: 1.875em;
        }
    </style>
</head>

<body>
    <p>I am first child.</p>
    <p>I am second child.</p>
    <p>I am third child.</p>
    <p>I am last child.</p>
</body>

</html>

Output:

Example 2: Styling the First Child of Multiple Parent Elements

This example demonstrates how to use the :first-child selector to style the first child of any parent element. Here, we style the first <p> tag in each <div> with red text and bold font.

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>
        /* Apply styles to the first child of any parent */
        p:first-child {
            color: red;
            font-weight: bold;
        }
    </style>
</head>

<body>
    <div>
        <p>This is the first paragraph.</p>
        <p>This is the second paragraph.</p>
    </div>
    <div>
        <span>Not a paragraph.</span>
        <p>This is the first paragraph in the second div.</p>
        <p>This is the second paragraph in the second div.</p>
    </div>
</body>

</html>

Output:

first-child
first child in CSS Example Output

Next Article

Similar Reads