Search code examples
htmlcsshoverbackground-color

Alter the color of table-row on hover when color set


I have an http table created dynamically by the server from data from a database. Depending on some values, the server sets the table row style="background-color:#RRGGBB". This value is from a string in the database, so CSS is not an option.
This all works nice and well, but this overrides the CSS which sets the background-color for hovering on a table row.

In this case, how do I change the color of the table row on hover, perferably while maintaining some resemblance to the color from the database?

table tr:nth-child(2n):hover {
  background-color: silver;
}

table tr:nth-child(2n+1):hover {
  background-color: gray;
}

table tr:nth-child(2n) {
  background-color: #DDDDEE;
}

table tr:nth-child(2n+1) {
  background-color: #CCCCDD;
}
<table width="100%">
  <tr>
    <td>Line1</td>
  </tr>
  <tr>
    <td>Line2</td>
  </tr>
  <tr>
    <td>Line3</td>
  </tr>
  <tr style="background-color:#FFDDDD;">
    <td>Line4 - With color, no hover effect</td>
  </tr>
  <tr style="background-color:#DDFFDD;">
    <td>Line5 - With color, no hover effect</td>
  </tr>
  <tr>
    <td>Line6</td>
  </tr>
  <tr>
    <td>Line7</td>
  </tr>
  <tr>
    <td>Line8</td>
  </tr>
</table>


Solution

  • You can apply a partially-transparent box-shadow to each element on hover.

    table tr:hover {
        box-shadow: inset 0 0 0 99999px rgba(0,0,0,0.2);;
    }
    
    table tr:nth-child(2n) {
      background-color: #DDDDEE;
    }
    
    table tr:nth-child(2n+1) {
      background-color: #CCCCDD;
    }
    <table width="100%">
      <tr>
        <td>Line1</td>
      </tr>
      <tr>
        <td>Line2</td>
      </tr>
      <tr>
        <td>Line3</td>
      </tr>
      <tr style="background-color:#FFDDDD;">
        <td>Line4 - With color, no hover effect</td>
      </tr>
      <tr style="background-color:#DDFFDD;">
        <td>Line5 - With color, no hover effect</td>
      </tr>
      <tr>
        <td>Line6</td>
      </tr>
      <tr>
        <td>Line7</td>
      </tr>
      <tr>
        <td>Line8</td>
      </tr>
    </table>