How to change CSS style of table column when mouseover?

2

How to change the CSS style (backgrounc-color) of an entire column when hovering, using CSS only ?

The table in question is as follows:

<table class="un table">
    <caption>Título da tabela</caption>
    <thead>
        <tr>
            <th>Coluna 1</th>
            <th>Coluna 2</th>
            <th>Coluna 3</th>
            <th>Coluna 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>L1 X C1</td>
            <td>L1 X C2</td>
            <td>L1 X C3</td>
            <td>L1 X C4</td>
        </tr>
        <tr>
            <td>L2 X C1</td>
            <td>L2 X C2</td>
            <td>L2 X C3</td>
            <td>L2 X C4</td>
        </tr>
        <tr>
            <td>L3 X C1</td>
            <td>L3 X C2</td>
            <td>L3 X C3</td>
            <td>L3 X C4</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Total C1</td>
            <td>Total C2</td>
            <td>Total C3</td>
            <td>Total C4</td>
        </tr>
    </tfoot>
</table>

In case of hovering over one of the columns, change the background-color of the entire column, including the header and the footer.

    
asked by anonymous 13.06.2016 / 21:49

1 answer

5

Using only CSS, you can do a fake using the after pseudo-element, see example:

table {
  overflow: hidden;
  border-collapse: collapse;
  border:solid red;
  border-width    : 1px 2px 1px 1px;
}
table caption {
  background-color:#fff;  
}
tr:hover {
  background-color: #ffa;
}

td, th {
  position: relative;
  
}
td:hover::after,
th:hover::after {
  content: "";
  position: absolute;
  background-color: #ffa;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}
<table class="un table">
    <caption>Título da tabela</caption>
    <thead>
        <tr>
            <th>Coluna 1</th>
            <th>Coluna 2</th>
            <th>Coluna 3</th>
            <th>Coluna 4</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>L1 X C1</td>
            <td>L1 X C2</td>
            <td>L1 X C3</td>
            <td>L1 X C4</td>
        </tr>
        <tr>
            <td>L2 X C1</td>
            <td>L2 X C2</td>
            <td>L2 X C3</td>
            <td>L2 X C4</td>
        </tr>
        <tr>
            <td>L3 X C1</td>
            <td>L3 X C2</td>
            <td>L3 X C3</td>
            <td>L3 X C4</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Total C1</td>
            <td>Total C2</td>
            <td>Total C3</td>
            <td>Total C4</td>
        </tr>
    </tfoot>
</table>

Sources: Simple CSS-Only Row and Column Highlighting e Stackoverflow

    
13.06.2016 / 22:27