Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color TD after hover

Tags:

html

css

For example, I have table with 1 row and many cells in this row.

<table>
  <tr>
    <td></td>
    <td class="red"></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

With JS I choose one cell and apply some class to it, which colors this cell. What do I need? I need color (select) cells before clicks. When I hover on last cell, for example, I need color cells between cell with class="red" and cell with hover. Something like

.red + :hover {
    background: green;
}

If I mouseenter in left side, before cell with class="red" the cell also needs to color between hover (include hover) and cell with some class. Can it be done only using CSS? In real situation I have many rows and many cells.

JSFiddle - https://jsfiddle.net/ssq8dzje/

like image 540
Luntegg Avatar asked Dec 14 '22 05:12

Luntegg


1 Answers

CSS only solution is here! =D

table {
    border-collapse: collapse;
    width: 100%;
}
td {
    border: 1px solid #000;
    cursor: pointer;
    height: 30px;
}
.red {
    background: #f33 !important;
}
td:hover {
    background: #22f !important;
}

tr:hover td.red ~ td,
tr:hover td:hover ~ td {
    background: green;
}

td.red ~ td:hover ~ td,
td:hover ~ td.red ~ td,
tr:hover td.red:hover ~ td {
    background: transparent;
}
<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td class="red"></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

It is rather hackish but it works at least. It might be possible to reduce the number of selectors as well, but I'm not bothered about it for now.

like image 186
Midas Avatar answered Dec 30 '22 02:12

Midas