Martin C.
Martin C.

Reputation: 73

CSS nth-child does not work

I know this question has been asked many times but I can't figure out the problem anyway, so this is my html:

    <table class="UMLTable">
        <tr>
            <th>Table<th>
        </tr>
        <tr>
            <td>Attribute 1<td>
        </tr>
        <tr>
            <td>Attribute 1<td>
        </tr>
        <tr>
            <td>Attribute 1<td>
        </tr>
        </tr>
    </table>

So why this line does not work:

.UMLTable td:nth-child(even){
    background-color:blue;
}

Upvotes: 6

Views: 16035

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

Try to use the tr element instead of td like this:

.UMLTable tr:nth-child(even) td {
    background-color:blue;
}

JSFIDDLE DEMO

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241278

You need to select the nth tr element rather than the child td element.

Your selector should be:

.UMLTable tr:nth-child(even) td {
    background-color:blue;
}

The reason your CSS isn't working as expected is because the td elements aren't siblings.

.UMLTable tr:nth-child(even) td {
  background-color: blue;
}
<table class="UMLTable">
  <tr>
    <th>Table
      <th>
  </tr>
  <tr>
    <td>Attribute 1
      <td>
  </tr>
  <tr>
    <td>Attribute 1
      <td>
  </tr>
  <tr>
    <td>Attribute 1
      <td>
  </tr>
  </tr>
</table>

Upvotes: 11

Related Questions