Home

Published

- 2 min read

CSS :first-of-type - How to use it

img of CSS :first-of-type - How to use it

With the CSS pseudo selector :first-of-type you can target the first type of element within its container.

It targets the first element of its type among a group of sibling elements.

“type” means the element type, for example, p, div, a, img, etc.

The :first-of-type pseudo-class selects the first element of its type within its parent container. This means it targets the first occurrence of a specific HTML tag among its siblings

CSS first of type

For example, to select the first p in the body, you’d write:

   body p:first-of-type {
	font-size: 1.25em;
}
   <body>
	<p>This will have a bigger font-size</p>
	<p>This no</p>
</body>

or another example:

   div p:first-of-type {
	color: blue;
}

This will only style the first <p> inside every <div>, not styling any other <p> elements.

How Is :first-of-type Different From :first-child?

At first glance, :first-of-type and :first-child might seem similar, but they serve different purposes:

  • :first-child: Matches the first child element, regardless of its type.
  • :first-of-type: Matches the first child of a specific type.

Here’s an example to clarify:

   <div>
	<h1>Heading</h1>
	<p>First paragraph</p>
	<p>Second paragraph</p>
</div>

div :first-child matches <h1>. div p:first-of-type matches the first <p>.

Browser Support

The :first-of-type pseudo-class is widely supported in all modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. However, for older versions of Internet Explorer (IE8 and below), it’s not supported.