Rockmaninoff Rockmaninoff - 1 month ago 9
CSS Question

How to deal with `rowspan` and background colors within a table?

I have a generic HTML table with some CSS background color styling. When a user hovers over a row, the background color of all cells in that row is changed to a light gray.

I have a cell in my top row that spans three rows. When I hover over the top row, the cell is shaded appropriately. However, when hovering over the second and third rows, the cell is not shaded.

Is it possible to shade the cell within the 2nd or 3rd row? How would I do that?

Relevant code:

style.css

td {
border: black 1px solid;
text-align: center;
padding-left: 5px;
padding-right: 5px;
}

tr:hover td {
background-color: #DDD;
}

th {
border: none;
}


table.html

<tr>
<td>Row 1:Col 1</td>
<td>Row 1:Col 2</td>
<td rowspan="3">Row 1/2/3:Col3</td>
</tr>
<tr>
<td>Row 2:Col 1</td>
<td>Row 2:Col 2</td>
</tr>
<tr>
<td>Row 3:Col 1</td>
<td>Row 3:Col 2</td>
</tr>

Answer

It can be accomplished using JavaScript like so:

<style type="text/css">
td {
    border: black 1px solid;
    text-align: center;
    padding-left: 5px;
    padding-right: 5px
}

tr:hover td {
    background-color: #DDDDDD;
}

th {
    border: none;
}

</style>
<script type="text/javascript">

function shadeCell( cellName )
{
    document.getElementById(cellName).style.backgroundColor = '#DDDDDD';
}

function unShadeCell( cellName )
{
    document.getElementById(cellName).style.backgroundColor = '';
}

</script>
<table>
<tr onMouseOver="shadeCell('bigCell')" onMouseOut="unShadeCell('bigCell')">
    <td>Row 1:Col 1</td>
    <td>Row 1:Col 2</td>
    <td rowspan="3" id="bigCell">Row 1/2/3:Col3</td>
</tr>
<tr onMouseOver="shadeCell('bigCell')" onMouseOut="unShadeCell('bigCell')">
    <td>Row 2:Col 1</td>
    <td>Row 2:Col 2</td>
</tr>
<tr onMouseOver="shadeCell('bigCell')" onMouseOut="unShadeCell('bigCell')">
    <td>Row 3:Col 1</td>
    <td>Row 3:Col 2</td>
</tr>
</table>

I am not sure how one can accomplish what you want by just plain HTML / CSS. Btw, you can simplify the above JavaScript using jQuery - would save you some typing.

Best, Kamran