Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

nth-child does not work with table elements

WHY ON EARTH has this question been closed? How is someone supposed to know that a question titled "What’s the difference between CSS classes .foo.bar (without space) and .foo .bar (with space)" is a duplicate for this? It doesn’t even mention "nth-child". You should change the title to make it a useful signpost for someone that has encounteded the same issue as me. If another question does that, cite that instead. This is zealous idiotic moderation.

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

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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>

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading