Risperidone Risperidone - 28 days ago 8
CSS Question

:nth-child definition & when it meets tr and caption

with the code below I found I'm confused with the definition of

:nth-child



The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.




tr:nth-child(2n) {
background-color: gray;
}
table {
margin-left: 20px;
margin-right: 20px;
border-spacing: 0px;
border: thin solid black;
caption-side: bottom;
border-collapse: collapse;
}
td,
th {
border: thin dotted gray;
padding: 5px;
}
caption {
font-style: italic;
padding-top: 8px;
}

<table>
<caption>content</caption>
<tr>
<th>table head</th>
</tr>
<tr>
<td>111111</td>
</tr>
<tr>
<td>222222</td>
</tr>
<tr>
<td>333333</td>
</tr>
<tr>
<td>444444</td>
</tr>
<tr>
<td>555555</td>
</tr>
<tr>
<td>666666</td>
</tr>
</table>





and the 111111, 333333, 555555 become gray. nothing changed after I delete the caption tag, but 222222, 4444444, 666666 become gray after I removed the tr tag of table title. Isn't :nth-child suppose to count "every" element of its parent?

Answer

The problem here is that your HTML is invalid. tr elements must be wrapped within either a thead, tbody or tfoot element, and most browsers will automatically fix this for you by sticking them in a tbody.

Your HTML on these browsers will actually end up looking like this:

<table>
  <caption>...</caption>
  <tbody>
    <tr>...</tr>
    ...
  </tbody>
</table>

And thus, deleting the <caption> element will have no impact on the positioning of your tr elements.

<table>
  <caption>content</caption>
  <tr>
    <th>table head</th>
  </tr>
  <tr>
    <td>111111</td>
  </tr>
  <tr>
    <td>222222</td>
  </tr>
  <tr>
    <td>333333</td>
  </tr>
  <tr>
    <td>444444</td>
  </tr>
  <tr>
    <td>555555</td>
  </tr>
  <tr>
    <td>666666</td>
  </tr>
</table>

If you inspect your <table> element, this is what you'll see:

enter image description here