CSS | :first-child Selector

The :first-child selector is used to select those elements which are the first-child elements. For :first-child selector the <!DOCTYPE> must be declared for IE8 and earlier versions.

Syntax:

:first-child {
    // CSS property
} 

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>first child selector</title>
        <style>
            h1 {
                color:green;
            }
            p:first-child {
                background-color: green;
                color:white;
                font-weight:bold;
            }
            body {
                text-align:center;
            }
        </style>
    </head>
    <body>
        <p>GeeksforGeeks</p>
        <h1>GeeksforGeeks</h1>
        <h2>:first-child Selctor</H2>
        <p>GeeksforGeeks</p>
        <div>
            <p>GFG</p>
            <p>Geeks</p>
        </div>
    </body>
</html>                    

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
    <head>
        <title>first child selector</title>
        <style>
            h1 {
                color:green;
            }
            h1, h2 {
                text-align:center;
            }
            li:first-child {
                background: green;
            
            body {
                width:70%;
            }
        </style>
    </head>
    <body>
        <h1>GeeksforGeeks</h1>
        <h2>:first-child Selector</h2>
        <ul>
            <li>Data Structure</li>
            <li>Computer Network</li>
            <li>Operating System</li>
        </ul>
        <ol>
            <li>Java</li>
            <li>Ruby</li>
            <li>Pascal</li>
        </ol>
    </body>
</html>                    

chevron_right


Output:

Supported Browsers: The browser supported by :first-child selector are listed below:

  • Apple Safari 3.1
  • Google Chrome 4.0
  • Firefox 3.0
  • Opera 9.6
  • Internet Explorer 7.0


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.