CSS :first-child-Pseudoklasse
Die CSS :first-child-Pseudoklasse wählt das Element aus, wenn es das erste Kind unter anderen Elementen ist.

Der Selektor :first-of-type kann verwendet werden, wenn der Benutzer den Stil auf das erste Absatz-Element anwenden möchte. Der :first-child-Selektor ist dem :first-of-type-Selektor zwar ähnlich, es gibt jedoch einen Unterschied: Sie erfüllen unterschiedliche Bedingungen. :first-child wählt ein Element nur dann aus, wenn es das erste Kind seines Elternelements ist, während :first-of-type das erste Element eines bestimmten Typs unter seinen Geschwisterelementen auswählt.
Version
Syntax
CSS :first-child Syntaxbeispiel
:first-child {
css declarations;
}Beispiel für die :first-child-Pseudoklasse mit dem <p>-Tag:
CSS :first-child Codebeispiel
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:first-child {
background-color: #1c87c9;
color: #fff;
}
</style>
</head>
<body>
<p>Lorem ipsum is simply dummy text...</p>
<h2>First-child selector example</h2>
<p>Lorem Ipsum is simply dummy text...</p>
</body>
</html>Beispiel für die :first-child-Pseudoklasse mit dem <li>-Tag:
CSS :first-child weiteres Codebeispiel
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
li:first-child {
background: #8ebf42;
}
</style>
</head>
<body>
<h2>:first-child selector example</h2>
<ul>
<li>Paris</li>
<li>Moscow</li>
<li>Rome</li>
</ul>
<ol>
<li>Paris</li>
<li>Moscow</li>
<li>Rome</li>
</ol>
</body>
</html>Beispiel für die :first-child-Pseudoklasse mit dem <ol>-Tag:
Beispiel für den :first-child-Selektor mit dem HTML ol-Tag
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
ol:first-child {
background: #8ebf42;
}
</style>
</head>
<body>
<ol>
<li>London</li>
<li>Paris</li>
<li>Rome</li>
</ol>
<ol>
<li>London</li>
<li>Paris</li>
<li>Rome</li>
</ol>
</body>
</html>Beispiel für die :first-child-Pseudoklasse mit dem <em>-Tag:
Beispiel für den :first-child-Selektor mit dem HTML em-Tag
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p em:first-child {
background: #82b534;
}
</style>
</head>
<body>
<h2>:first-child selector example</h2>
<article>
<p>Here is a <em>some</em> text. This is a <em>example</em>.</p>
<p>Here is a <em>some</em> text. This is a <em>example</em>.</p>
<p>Here is a <em>some</em> text. This is a <em>example</em>.</p>
</article>
</body>
</html>Beispiel für die :first-child-Pseudoklasse mit dem <ul>-Tag:
Beispiel für den :first-child-Selektor mit dem HTML ul-Tag
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
ul li {
color: blue;
}
ul li:first-child {
color: #8ebf42;
font-weight: bold;
}
</style>
</head>
<body>
<h2>:first-child selector example</h2>
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>
List Item 3
<ul>
<li>List Item 3.1</li>
<li>List Item 3.2</li>
<li>List Item 3.3</li>
</ul>
</li>
</ul>
</body>
</html>Praxis
Was stellt die :first-child-Pseudoklasse in CSS dar?