I would like to have the top and bottom border of a tr
to change colour when I hover over it. The problem that I am having is that the tr
above the hovering one is overriding the hover styles (at least that is what I think is happening).
In my example here, the first item is hovering correctly, but in the second and third ones only the bottom border is highlighting:
table {
border-collapse: collapse;
}
th {
background-color: rgb(231, 231, 231);
}
td {
border-bottom: 2px solid rgb(214, 214, 214);
border-top: 2px solid rgb(214, 214, 214);
}
table tr:hover td {
border-bottom: 2px solid red;
border-top: 2px solid red;
}
<table>
<tr>
<th>COMPANY</th>
<th>CONTACT</th>
<th>COUNTRY</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</table>
If you want to keep your 2 px borders, you need to get rid of the collapse and then remove the border-padding. You can then use a sibling selector to change the correct borders on hover.
In the below, I have just added a thead and tbody to your table so that we know only the body elements will change when hovered
table {
border-spacing:0;
}
th {
background-color: rgb(231, 231, 231);
}
td {
border-top: 2px solid rgb(214, 214, 214); /* make all cells have a top border */
}
tbody tr:last-child td {
border-bottom: 2px solid rgb(214, 214, 214); /* make the last row also have a bottom border */
}
tbody tr:hover td {
border-color: red; /* change all borders to red on hover (mainly because of the last child bottom border */
}
tbody tr:hover + tr td {
border-top-color: red; /* change any cells without a bottom border - make the next row have top border go red (so it looks like current row bottom border) */
}
<table>
<thead>
<tr>
<th>COMPANY</th>
<th>CONTACT</th>
<th>COUNTRY</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
</tbody>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With