CSS :first-of-type

The CSS :first-of-type pseudo-class selects the first child element of the specified element type of its parent. For example, the following CSS code applies the style to the first child of type P of its parent:

p:first-of-type {background-color: black; color: white; padding: 8px;}

CSS :first-of-type example

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

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:first-of-type {background-color: orchid; color: white; padding: 10px;}
   </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>
   
</body>
</html>
Output

This is para one.

This is para two.

This is para one, inside DIV.

In the above example, the selector "p:first-of-type" targets the first instance of the <p> element within its parent container. In this example, there are two <p> elements that are siblings, and a third <p> element that is nested within a <div> element.

The CSS rules that follow the selector set the background color of the first paragraph element to orchid, the text color to white, and add padding of 10 pixels to the top, right, bottom, and left sides of the element.

Therefore, in this example, the first paragraph element in the document and the first paragraph element inside the <div> element will have an orchid background color, white text color, and padding of 10 pixels. The second paragraph element in the document will not be affected by this styling.

CSS :first-of-type syntax

The general form or the syntax of the ":first-of-type" pseudo-class in CSS is as follows:

selector:first-of-type {
   // CSS declarations
}

Since the :first-of-type pseudo-class selects the first element of a given type within its container element, therefore it is written as a suffix to the element selector, separated by a colon.

For example, p:first-of-type selects the first <p> element within its parent element, regardless of its class or ID.

The :first-of-type pseudo-class can be used with any element type, such as <h1>, <h2>, <div>, <span>, etc. It is a useful tool for targeting specific elements within a container, especially when the elements are siblings of different types.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!