CSS :hover for highliting multiple td cells

Viewed 862

In a table, upon hovering on one td cell, I want to highlight multiple td cells in the same row.

What I have currently is to use classes on each td like this:

        <tr>
            <td>v1_a</td>
            <td class='c1'>v1_b1</td>
            <td class='c1'>v1_b2</td>
            <td class='c2'>v1_c1</td>
            <td class='c2'>v1_c2</td>
        </tr>

and have CSS like this:

tbody td.c1:hover,
tbody td.c1:hover ~ .c1,
tbody td.c2:hover,
tbody td.c2:hover ~ .c2 {
    background-color: #CCffff;
}

then I can partially achieve what I want: JSFiddle

However, it is not exactly what I want. It highlights both col_b1 and col_b2 when I hover on col_b1, but not when I hover on col_b2. I want to highlight both of these columns whenever the pointer is on one of the cells.

Is there a simple solution ideally using only CSS?

2 Answers

Please use javascript to achieve.

I added an attribute as same-group elements identification to make it more sustainable.

$('.highlight').on('mouseover', function() {
  $('.highlight').removeClass('hover');
  $('.highlight[data-cell="'+$(this).data('cell')+'"]').addClass('hover');
});
td {
  border: 1px solid;
}
.hover {
  background-color: #ff0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>v1_a</td>
    <td class="highlight" data-cell="c1">c1</td>
    <td class="highlight" data-cell="c1">c1</td>
    <td class="highlight" data-cell="c2">c2</td>
    <td class="highlight" data-cell="c2">c2</td>
  </tr>
  <tr>
    <td>v1_a</td>
    <td class="highlight" data-cell="c3">c3</td>
    <td class="highlight" data-cell="c3">c3</td>
    <td class="highlight" data-cell="c4">c4</td>
    <td class="highlight" data-cell="c4">c4</td>
  </tr>
</table>

If you want to highlight full row, when hovering over any of the cell. Then write

tr:hover {background-color: #f5f5f5;}

in css file. If you are not using css file and writing all the styling in html file theln write in head

<style>
   tr:hover {background-color: #f5f5f5;}
</style>

I hope this will be helpful for you.

Related