CSS :first-of-type-Pseudoklasse
Die CSS- :first-of-type-Pseudoklasse wählt ein Element aus, das unter seinen Geschwisterelementen das erste Element seines Typs ist. Sie ist äquivalent zu [:nth-of-type(1)](/learn-css/nth-of-type.html).

Der Selektor :first-of-type wird oft mit :first-child verglichen, unterscheidet sich jedoch im Geltungsbereich. Während :first-child ein Element basierend auf seiner Position unter allen Kindern unabhängig vom Typ auswählt, trifft :first-of-type nur zu, wenn es das erste unter Geschwistern des gleichen Elementtyps ist. Beide Selektoren haben die gleiche CSS-Spezifität.
DANGER
Ab Selectors Level 4 muss das ausgewählte Element nicht zwingend einen Elternknoten im DOM haben, um übereinzustimmen.
Version
Syntax
CSS :first-of-type-Syntax
:first-of-type {
css declarations;
}Beispiel für den :first-of-type-Selektor:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:first-of-type {
background: #8ebf42;
}
</style>
</head>
<body>
<h2>:first-of-type selector example</h2>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
</body>
</html>Beispiel für den :first-of-type-Selektor mit dem <article>-Tag:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:first-of-type {
font-size: 22px;
color: #777777;
}
</style>
</head>
<body>
<h2>:first-of-type selector example</h2>
<article>
<h2>This is a title.</h2>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. .</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. .</p>
</article>
</body>
</html>Beispiel für den :first-of-type-Selektor mit einigen HTML-Tags:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p {
margin: 0;
}
article:first-of-type {
background-color: #777777;
color: #ffffff;
}
</style>
</head>
<body>
<h2>:first-of-type selector example</h2>
<article>
<p>This is a first element!</p>
<p>This <em>nested 'em' is first</em>!</p>
<p>This <strong>nested 'strong' is first</strong>, but this <strong>nested 'strong' is last</strong>!</p>
<p>This <span>nested 'span' gets styled</span>!</p>
<q>This is a 'q' element!</q>
<p>This is a last element.</p>
</article>
<article>
<p>This is a second article.</p>
</article>
</body>
</html>Browser-Kompatibilität
| Browser | Version |
|---|---|
| Chrome | 1.0 |
| Firefox | 1.0 |
| Safari | 1.0 |
| Edge | 12.0 |
| Opera | 7.0 |
| IE | 9.0 |
Praxis
Was ist die korrekte Definition und Verwendung der CSS-Pseudoklasse :first-of-type?