The :first-of-type CSS pseudo-class represents the first element of its type among a group of sibling elements.
/* Selects the first <p> to appear inside a parent element
regardless of its position inside the siblings */
p:first-of-type {
color: red;
}
Note: As originally defined, the selected element had to have a parent. Beginning with Selectors Level 4, this is no longer required.
Syntax
:first-of-type
Examples
Example 1: Simple first paragraph
Let's consider the following HTML:
<h2>Heading</h2> <p>Paragraph</p> <p>Paragraph</p>
And the following CSS:
p:first-of-type {
color: red;
}
This gives the following result — the first paragraph only is colored red, as it is the first element of type paragraph to appear inside the body:
Example 2: Assumed universal selector
This example shows how the universal selector is assumed when no simple selector is written.
First, some HTML:
<div> <span>This `span` is first!</span> <span>But this `span` isn't.</span> <span>This <em>nested `em` is</em>!</span> <span>And so is this <span>nested `span`</span>!</span> <b>This `b` qualifies!</b> <span>This final `span` does not.</span> </div>
Now, the CSS:
div :first-of-type {
background-color: lime;
}
The result looks like this:
Specifications
| Specification | Status | Comment |
|---|---|---|
| Selectors Level 4 The definition of ':first-of-type' in that specification. |
Working Draft | Matching elements are not required to have a parent. |
| Selectors Level 3 The definition of ':first-of-type' in that specification. |
Recommendation | Initial definition. |
Browser compatibility
| Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
| Basic support | 1.0 | (Yes) | 3.5 (1.9.1) | 9.0 | 9.5 | 3.2 |
| Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | 2.1 | (Yes) | 1.0 (1.9.1) | 9.0 | 10.0 | 3.2 |
See also
Document Tags and Contributors
Tags:
Contributors to this page:
chrisdavidmills,
mfluehr,
CarloMartini,
erikadoyle,
fengyue1013,
Sebastianz,
jsx,
MusikAnimal,
kscarfone,
Sheppy,
joyously,
teoli,
brianloveswords,
McGurk,
Miken32
Last updated by:
chrisdavidmills,