CSS :nth-child()-Pseudoklasse
Die :nth-child()-Pseudoklasse wählt Elemente basierend auf ihrem Index aus und fügt ihnen Styles hinzu.
:nth-child() kann durch eine Zahl, ein Schlüsselwort oder eine Formel angegeben werden.
Schlüsselwortwerte
odd
Repräsentiert die Elemente, deren numerische Position ungerade ist (z. B. 1, 3, 5, 7 usw.).
even
Repräsentiert die Elemente, deren numerische Position gerade ist (z. B. 2, 4, 6, 8 usw.).
Funktionale Notation
<An+B>
Repräsentiert die Elemente, deren numerische Position dem Muster An+B entspricht (für jeden positiven ganzzahligen oder null Wert von n). Der Index des ersten Elements ist 1, und n in der Formel beginnt bei 0. Die Werte A und B müssen ganzzahlig sein.
Version
Syntax
CSS :nth-child()-Syntax
:nth-child() {
css declarations;
}Beispiel für den :nth-child-Selektor:
:nth-child()-Codebeispiel
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-child(3) {
background: #ccc;
}
</style>
</head>
<body>
<h2>:nth-child selector example</h2>
<div>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</div>
</body>
</html>Beispiel für die Schlüsselwörter "odd" und "even":
CSS :nth-child() odd, even
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
p:nth-child(odd) {
background: #1c87c9;
color: #eeeeee;
}
p:nth-child(even) {
background: #666666;
color: #eeeeee;
}
</style>
</head>
<body>
<p>The first paragraph.</p>
<p>The second paragraph.</p>
<p>The third paragraph.</p>
</body>
</html>Praxis
Welche Funktion hat der nth-child()-Selektor in CSS?