CSS :first-child | Style First Child Element

The CSS :first-child pseudo-class selects the first child element of its parent.

CSS :first-child syntax

The syntax of the ":first-child" pseudo-class in CSS is as follows:

parent-element :first-child {
   /* CSS styles */
}

The parent-element refers to the parent element of the first child element that you want to style. For example, the following CSS code applies style to allĀ <P> elements that are, of course, the first child of their parent element:

p:first-child {background-color: #ccc; padding: 10px;}

CSS :first-child example

Consider the following code as an example demonstrating the ":first-child" pseudo-class in CSS:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:first-child {background-color: turquoise; padding:10px; text-align: center;}
      li:first-child {color: red;}
   </style>
</head>
<body>

   <p>This is para one.</p>
   <p>This is para two.</p>
   <div>
      <p>This is para one, inside DIV.</p>
   </div>
   <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
   </ul>
   
</body>
</html>
Output

This is para one.

This is para two.

This is para one, inside DIV.

  • one
  • two
  • three

In the above example, the first p element is selected using

p:first-child

selector and its background color is set to turquoise, padding is set to 10 pixels, and text alignment is set to center. This means that the first paragraph will have a turquoise background color, padding of 10 pixels, and the text inside the paragraph will be center-aligned.

Similarly, the

li:first-child

selector selects the first child li element of a parent element. In the given code, the first li element inside the ul element is selected and its color is set to red. This means that the text inside the first li element will be displayed in red color.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!