0

I want to color the rows of my table with differents colors so I'm using this

table#news tr:nth-child(even) {      
  background-color: red;
}
table#news tr:nth-child(odd) {
  background-color: green;
}

It works well with this kind of structure

<table id="news">
<tr><td>Row 1</td></tr>
<tr><td>Row 2</td></tr>
<tr><td>Row 3</td></tr>
</table>

But now I work with this kind of table.

<table id="news">
  <tr>
    <td>
      <tr><td>1</td></tr>
      <tr><td>2</td></tr>
    </td>
  </tr>
</table>

The style is also applied for the rows inside the rows.

How can I proceed to apply the alternate color only for the first level of <tr> ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Atnaize
  • 1,766
  • 5
  • 25
  • 54

1 Answers1

1

Try this:

table#news > tr:nth-child(even) {      
  background-color: red;
}
table#news > tr:nth-child(odd) {
  background-color: green;
}

> Means that it's a #news has to be a direct parent of the tr.

In order for this to work, you also have to add the tbody selector.

table#news tbody > tr:nth-child(even) {      
  background-color: red;
}
table#news tbody > tr:nth-child(odd) {
  background-color: green;
}

tbody element is automatically added by the browser.

Anyway, the above still won't work because you can not nest a tr inside a td. What you have to do is create an entire new table inside the td. See this: Html table tr inside td

Run the code snippet below and look at the source code.

table.news > tbody > tr:nth-child(even) {
  background-color: red;
}
table.news > tbody > tr:nth-child(odd) {
  background-color: green;
}
<table class="news">
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>Row 3</td>
  </tr>
</table>

<table class="news">
  <tr>
    <td>
      Test
      <tr>
        <td>Row 1</td>
      </tr>
      <tr>
        <td>Row 2</td>
      </tr>
      <tr>
        <td>Row 3</td>
      </tr>
    </td>
  </tr>
</table>

<h1> Fixed </h1>

<table class="news">
  <tr>
    <td>Row 1</td>
  </tr>
  <tr>
    <td>Row 2</td>
  </tr>
  <tr>
    <td>Row 3</td>
  </tr>
</table>

<table class="news">
  <tr>
    <td>
      Test
      <table>
        <tr>
          <td>Row 1</td>
        </tr>
        <tr>
          <td>Row 2</td>
        </tr>
        <tr>
          <td>Row 3</td>
        </tr>
      </table>
    </td>
  </tr>
</table>
Community
  • 1
  • 1
XCS
  • 27,244
  • 26
  • 101
  • 151