Search code examples
cssrowcell

Change only one cell on tr hover


I have 5 cells in each row. I can change the background on all 5 cells with:

tr:hover {
   background: some_color;
} 

But I want cell number 5 to be a different color. Need answer using css, js, or jquery.


Solution

  • You may specify the fifth cell using :nth-of-type pseudo class

    tr:hover td:nth-child(5) {
      background-color: some_color;
    }
    

    tbody tr:hover {
      background-color: salmon;
    }
    
    tbody tr:hover td:nth-of-type(5) {
      background-color: steelblue;
    }
    <table border="1">
      <thead>
        <tr>
          <th>Header 1</th>
          <th>Header 2</th>
          <th>Header 3</th>
          <th>Header 4</th>
          <th>Header 5</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Cell 1-1</td>
          <td>Cell 1-2</td>
          <td>Cell 1-3</td>
          <td>Cell 1-4</td>
          <td>Cell 1-5</td>
        </tr>
        <tr>
          <td>Cell 2-1</td>
          <td>Cell 2-2</td>
          <td>Cell 2-3</td>
          <td>Cell 2-4</td>
          <td>Cell 2-5</td>
        </tr>
        <tr>
          <td>Cell 3-1</td>
          <td>Cell 3-2</td>
          <td>Cell 3-3</td>
          <td>Cell 3-4</td>
          <td>Cell 3-5</td>
        </tr>
      </tbody>
    </table>