In this example we are going to see how when moving the cursor over a table we make the effect of highlighting table rows with CSS. That is, the row on which the cursor is located lights up, or changes color.
The first thing will be to generate a table in HTML. So let’s see what this table would look like:
…
| Country | Capital | Surface | Inhabitants |
|---|---|---|---|
| Spain | Madrid | 504,645 km2 | 46.6 M |
As always you have to see the elements HTML that form the table. This is important as we will be styling these elements. The important ones are table, tr, td, th,… In this case we are going to stay with tr which represents the row and will serve us for the effect we want to create.
We have already said that the effect of highlighting table rows with CSS we are going to execute it on the tr element, so our style sheet CSS will have to be assembled as follows:
table tr {
/* Styles */
}
What we are going to do is change the color of the row, so we will manipulate the attribute background-color, assigning a different value than the one they have.
table tr {
background-color: #f00;
}
But so far this code CSS what it does is turn all the rows red. And we only want it to be when we move with the cursor. In this case, the style must be told that it will be in the event that the hover selector. This is what represents the mouse passing over the element.
We modified our code again to add this effect.
table tr:hover {
background-color: #f00;
}
With this we would have achieved the effect of highlighting table rows with CSS. But we are going to add one more plus, which will be that when we go through the row the cursor becomes a pointer. In this case we will have to modify the cursor property and give it the value of pointer to achieve this effect.
This way our code CSS final that achieves the effect of highlighting table rows with CSS would look like this:
table tr:hover {
background-color: #f00;
cursor: pointer;
}
