0
0
CssHow-ToBeginner · 3 min read

How to Use first-of-type in CSS: Simple Guide

Use the :first-of-type pseudo-class in CSS to select the first element of a specific type among its siblings. For example, p:first-of-type targets the first <p> inside its parent container.
📐

Syntax

The :first-of-type selector targets the first sibling element of its type inside a parent. It matches the first element of the specified tag name among its siblings.

  • element:first-of-type: Selects the first element of its type.
  • :first-of-type can be combined with classes or IDs for more specific targeting.
css
element:first-of-type {
  /* CSS properties */
}
💻

Example

This example shows how to style only the first paragraph inside a container with a red color and bold text.

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>first-of-type Example</title>
<style>
  p:first-of-type {
    color: red;
    font-weight: bold;
  }
</style>
</head>
<body>
  <div>
    <p>This is the first paragraph and will be red and bold.</p>
    <p>This is the second paragraph and will have default style.</p>
    <p>This is the third paragraph and will have default style.</p>
  </div>
</body>
</html>
Output
A webpage with three paragraphs inside a container. The first paragraph text is red and bold, the others are normal black and regular weight.
⚠️

Common Pitfalls

One common mistake is confusing :first-of-type with :first-child. :first-of-type selects the first element of its type, regardless of other sibling types, while :first-child selects the very first child element of any type.

Also, :first-of-type only works with element types, not classes or IDs alone.

css
/* Wrong: selects first child regardless of type */
div > p:first-child {
  color: blue;
}

/* Correct: selects first <p> element inside div */
div > p:first-of-type {
  color: red;
}
📊

Quick Reference

SelectorDescription
element:first-of-typeSelects the first element of that type among siblings
:first-childSelects the very first child element regardless of type
element:first-of-type.classSelects the first element of that type with a specific class
element:first-of-type:hoverApplies styles when hovering over the first element of that type

Key Takeaways

Use :first-of-type to style the first element of a specific tag inside a parent.
:first-of-type differs from :first-child by focusing on element type, not position alone.
It works only with element types, not classes or IDs by themselves.
Combine :first-of-type with other selectors for precise styling.
Test in browser DevTools to see which elements are selected.