CSS : Pseudo-classe :first-child
La pseudo-classe CSS :first-child sélectionne l'élément s'il est le premier enfant parmi les autres éléments.

Le sélecteur :first-of-type peut être utilisé si l'utilisateur souhaite sélectionner et appliquer un style au premier paragraphe. Le sélecteur :first-child est en fait similaire à :first-of-type, mais il y a une différence : ils correspondent à des conditions différentes. :first-child ne correspond à un élément que s'il est le premier enfant de son parent, tandis que :first-of-type correspond au premier élément de son type spécifique parmi ses frères et sœurs.
Version
Syntaxe
Exemple de syntaxe CSS :first-child
:first-child {
css declarations;
}Exemple de la pseudo-classe :first-child avec la balise <p> :
Exemple de code CSS :first-child
<!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>Exemple de la pseudo-classe :first-child avec la balise <li> :
Autre exemple de code CSS :first-child
<!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>Exemple de la pseudo-classe :first-child avec la balise <ol> :
Exemple du sélecteur :first-child avec la balise HTML ol
<!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>Exemple de la pseudo-classe :first-child avec la balise <em> :
Exemple du sélecteur :first-child avec la balise HTML em
<!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>Exemple de la pseudo-classe :first-child avec la balise <ul> :
Exemple du sélecteur :first-child avec la balise HTML ul
<!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>Pratique
Que représente la pseudo-classe :first-child en CSS ?