CSS Selector :first-child








The :first-child selector matches the first child element.

:first-child is a Pseudo-class and it applies to any element that is the first child of another element.

With :first-child pseudo-class, an element is matched only when it is the first child of another element.

For example, p:first-child will select any p element that is the first child of some other element.

It does not select whatever element is the first child of a paragraph; for that, we can use p > *: first-child.

Examples:

body *:first-child {font-weight: bold;}
p:first-child  {font-size: 125%;}

Summary

CSS Version
2




CSS Syntax

:first-child { 
   style properties 
}

Browser compatibility

:first-child Yes 7.0 Yes Yes Yes

Example

An example showing how to use :first-child CSS selector.

<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        :first-child { <!--  www.j  av a 2 s  . c om-->
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 

        <p>I like <span>HTML</span> and <span>CSS</span>.</p> 

    </body> 
</html>

Click to view the demo





Example 2

We can use the :first-child selector as a modifier and combining it with other selectors.

<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
        <style type="text/css"> 
        p > span:first-child { <!-- w  w  w  .  j  a  v  a  2s . co m-->
            border: thin black solid; 
            padding: 4px; 
        } 
        </style> 
    </head> 
    <body> 
        <p>I like <span>HTML</span> and <span>CSS</span>.</p> 
    </body> 
</html>

Click to view the demo

Match the first element in all container elements

In the following example, the selector matches the first <i> element in all <p> elements:

<html>
    <head>
        <style> 
            p > i:first-child<!-- w  w  w.  j  a  va  2s .c  om-->
            {
               font-weight:bold;
            }
        </style>
    </head>
    
    <body>
        <p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
        <p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
    </body>
</html>

Click to view the demo

Match all elements in first child elements

In the following example, the selector matches all <i> elements in <p> elements that are the first child of another element.

<html>
    <head>
    <style> 
        p:first-child i<!--from w  w  w . j  a v  a 2 s.  c o  m-->
        {
            color:blue;
        }
    </style>
    </head>
    <body>
        <p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
        <p>HTML is <i>easy</i>. CSS is <i>easy</i>.</p>
    </body>
</html>

Click to view the demo