-3

When using :nth-child(1) on a table, Why does the style not only apply to the first cell?

enter image description here

<!DOCTYPE html>
<html>
<head>
<style> 

.header:nth-child(1) {
  background: lightgreen;
}

</style>
</head>
<body>

 <table>
   <tr class="header">
     <th>Company</th>
     <th>Contact</th>
     <th>Country</th>
   </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table> 

</body>
</html>
blackgreen
  • 34,072
  • 23
  • 111
  • 129
geotheory
  • 22,624
  • 29
  • 119
  • 196
  • 2
    You probably mean `.header > :nth-child(1)`. `.header:nth-child(1)` means select `.header` elements which are also the first child of another element. – InSync Mar 31 '23 at 09:36

1 Answers1

0

you probably need to declare the element selector for applying styles.

<!DOCTYPE html>
<html>
<head>
<style> 

.header > :nth-child(1) {
  background: lightgreen;
}

</style>
</head>
<body>

 <table>
   <tr class="header">
     <th>Company</th>
     <th>Contact</th>
     <th>Country</th>
   </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
</table> 

</body>
</html>
Dakshank
  • 689
  • 4
  • 15