CSS - Pseudo-class :first-child



The CSS pseudo-class selector :first-child is used to select and style the first child element among a group of sibling elements.

Syntax

:first-child {
   /* ... */ 
}

CSS :first-child Example

Following example demonstrates use of :first-child pseudo-class, applied on <p> tag, under <div> parent element.

In this example, the CSS rules will only apply to the first <p> element found within a <div> element, leaving other <p> elements within the same container unaffected.

<html>
<head>
<style>
   p:first-child {
      color: black;
      background: yellow;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
   }
</style>
</head>
<body>
   <div>Parent element
      <p>first child looks different due to :first-child pseudo-class</p>
      <p>second child, so no change</p>
   </div>
   <div>Parent element
      <h3>h3 tag, so no change</h3>
      <p><b>p</b> tag, but not the first child.</p>
   </div>
</body>
</html>

Following example demonstrates use of :first-child pseudo-class, applied on <li> tag, under <ul> parent element.

In this example, the CSS rules will only apply to the first <li> element found within an <ul> element, leaving other <li> elements within the same container unaffected.

<html>
<head>
<style>
   ul li:first-child {
      color: black;
      background: yellow;
      font-weight: 600;
      font-size: 1em;
      font-style: italic;
      padding: 5px;
   }
   div {
      border: 2px solid black;
      margin-bottom: 5px;
      width: 300px;
   }
</style>
</head>
<body>
   <div>
      <ul>
         <li>One</li>
         <li>Two</li>
         <li>Three
            <ul>
               <li>Three 1</li>
               <li>Three 2</li>
               <li>Three 3</li>
            </ul>
         </li>      
      </ul>
   </div>
</body>
</html>
Advertisements