:first-child
La pseudo-class CSS :first-child
representa el primer element entre un grup d'elements germans.
/* Selecciona qualsevol <p> que sigui el primer element entre els seus germans */
p:first-child {
color: lime;
}
Nota: Com es va definir originalment, l'element seleccionat havia de tenir un pare. A partir dels Selectores Nivell 4, això ja no és necessari.
Sintaxi
:first-child
Exemples
Exemple bàsic
HTML
<div>
<p>This text is selected!</p>
<p>This text isn't selected.</p>
</div>
<div>
<h2>This text isn't selected: it's not a `p`.</h2>
<p>This text isn't selected.</p>
</div>
CSS
p:first-child {
color: lime;
background-color: black;
padding: 5px;
}
Resultat
Disseny d'una llista
HTML
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3
<ul>
<li>Item 3.1</li>
<li>Item 3.2</li>
<li>Item 3.3</li>
</ul>
</li>
</ul>
CSS
ul li {
color: blue;
}
ul li:first-child {
color: red;
font-weight: bold;
}
Resultat
Especificacions
Especificació | Estat | Comentari |
---|---|---|
Selectors Level 4 The definition of ':first-child' in that specification. |
Working Draft | No es requereix que els elements coincidents tinguin un pare. |
Selectors Level 3 The definition of ':first-child' in that specification. |
Recommendation | Cap canvi. |
CSS Level 2 (Revision 1) The definition of ':first-child' in that specification. |
Recommendation | Definició inicial. |
Navegadors compatibles
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help! (en-US)
Descripció | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Suport bàsic | 4.0 | (Yes) | 3.0 (1.9) | 7[1] | 9.5 | 4 |
No es requereix cap pare | 57 | ? | 51 (51)[2] | ? | 44 | ? |
Descripció | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Suport bàsic | (Yes) | (Yes) | (Yes) | 1.0 (1.9.1) | 7[1] | 10 | 3.1 |
No es requereix cap pare | 57 | 57 | 51.0 (51)[2] | ? | ? | 44 | ? |
[1] Internet Explorer 7 no actualitza els estils quan s'afegeixen elements dinàmicament. A Internet Explorer 8, si un element s'insereix de forma dinàmica fent clic en un enllaç, l'estil del primer fill no s'aplica fins que l'enllaç no ha perdut el focus.
[2] Veure errada 1300374.