CSS – Change Background Color of Table Row upon Hover

To change background color of the table row when user hovers over the row using mouse pointer, set the CSS background-color property with the required Color Value for the rows in table body with :hover selector.

The CSS code to set tbody tr:hover selector, for table rows, with required background color value is showing in the following.

</>
Copy
tbody tr:hover {
  background-color: yellow;
}

Examples

1. Set background color of table row to yellow on hover

In the following example, we take a table with two columns, three rows, and set the row’s background color to yellow when user hovers over a table row.

index.html

</>
Copy
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <style>
    tbody tr:hover {
      background-color: yellow;
    }
    table, th, td {
      border-collapse: collapse;
      padding: 10px;
    }
  </style>
</head>
<body>
  <table>
    <thead>
      <tr>
        <th>Fruit</th>
        <th>Quantity</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Apple</td>
        <td>32</td>
      </tr>
      <tr>
        <td>Banana</td>
        <td>48</td>
      </tr>
      <tr>
        <td>Cherry</td>
        <td>75</td>
      </tr>
    </tbody>
  </table>
</body>
</html>

Conclusion

In this CSS Tutorial, we learned how to use CSS :hover selector and background-color property to set a specific color for the table row’s background when mouse is hovered upon it, with examples.