Ponnarasu Ponnarasu - 3 months ago 13
CSS Question

Change background colour on mouse over of all tr which all are present after particular class using CSS

I have a table with multiple rows.I am using the first row as table header and differentiated it using CSS.

Now I want to change background colour for all the remaining rows with in that table on mouse over using CSS. But the header row background should not be changed.

HTML

<table border="1" width="100%" id="table1">
<tr class="headerStyle">
<td>Sl.No</td>
<td>Name</td>
<td>Code</td>
</tr>

<tr>
<td>1</td>
<td>Name1</td>
<td>Code1</td>
</tr>

<tr>
<td>2</td>
<td>Name2</td>
<td>Code2</td>
</tr>

<tr>
<td>3</td>
<td>Name3</td>
<td>Code3</td>
</tr>
</table>


CSS

.headerStyle {
color: #ffffff;
font-size: 13px;
text-align: center;
font-weight: 500;
background-color: #07889b;
}

.headerStyle + tr:hover {
background-color: #bedcfc;
}


I tried many suggestions from stackoverflow, but didn't worked.

I tried the above finally, but it changing the first row's background colour only.

Is there any possibility in CSS?
Thanks in advance.

Answer

+ is for adjacent sibling, you looking for the ~ (General sibling selectors.).

But for a correct semantic structure the header of a table should be in the thead tag of your table, and the rest of the rows should be in the tbody. The way you wrote it all of your tr element would be automatically placed in the tbody. And for the header you should use th and not td.

So your structure should look like that:

<table border="1" width="100%" id="table1">
  <thead>
    <tr>
      <th>Sl.No</th>
      <th>Name</th>
      <th>Code</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Name1</td>
      <td>Code1</td>
    </tr>

    <tr>
      <td>2</td>
      <td>Name2</td>
      <td>Code2</td>
    </tr>

    <tr>
      <td>3</td>
      <td>Name3</td>
      <td>Code3</td>
    </tr>
  </tbody>
</table>

If you structure your table that way you would have a correct semantic structure, and you would not have a problem with your css rules:

thead tr {
  color: #ffffff;
  font-size: 13px;
  text-align: center;
  font-weight: 500;
  background-color: #07889b;
}

tbody tr:hover {
  background-color: #bedcfc;
}

If you do not want to structure your code that way then the css rule would have to be:

.headerStyle ~ tr:hover {
    background-color: #bedcfc;
}