Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 463
Martin C. Avatar asked May 01 '15 18:05

Martin C.


2 Answers

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>
like image 123
Josh Crozier Avatar answered Sep 29 '22 13:09

Josh Crozier


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

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

JSFIDDLE DEMO

like image 22
Rahul Tripathi Avatar answered Sep 29 '22 14:09

Rahul Tripathi