Have you ever seen a lot of information in a table on the web and wish that you can highlight just one row of that table? Looking very large tables, with out the ability to interact with the table, can make it hard to read the information provided. With a little bit of CSS and the hover and first-child pseudo classes, you can make tables interactive again. You visitors can read information from the table quicker, and it gives your tables a little Web 2.0 flare. Best of all it is easier then you think.
First, lets make a table with some information.
| Age Group | Population | Percentage |
|---|---|---|
| 0 - 5 | 16146 | 6.2% |
| 5 - 9 | 15711 | 6.03% |
| 10 - 14 | 14947 | 5.74% |
The CSS for this effect is very simple, but very powerful. We are going to add the hover pseudo class to all the tr elements, that way when a user mouses over a cell in the table the entire row’s changes. To the user they are mousing over a cell in the table, but to the code they are mousing over the entire row. The following allows us to add this effect
tr:hover{
background-color: #FF0000;
color: #FFFFFF;
}
Simple right, well there is a little issue. When the user rolls over the table headers (th) they get the same effect. We don’t want this to occur, so this is where the first-child pseudo class comes into play. We can add both pseudo classes to tr entry in the style sheet to fix this “issue”.
tr:first-child:hover{
background-color: #FFFFFF;
color: #000000;
}
That will fix the issue with the table headers. To explain the code a little more, what is happening is the first-child pseudo class is being applied to the th elements since they are the first elements after the first tr element. The hover pseudo class will only be activated when the user mouses over the table header, and it is set with the default values for the attributes, before the hover pseudo class is activated. This code is actually being activated when the user mouses over it, but since the attributes are the same as when the user does not mouse over the table headers, the user does not even see the code in action.
If you wanted you could go a step further and add a hover pseudo class to the cell that the user is moused over of an additional effect. For this effect you could make the row either a different color, or make the row a lighter shade of the cell background color. Below is an example of the CSS code that will allow you to do this effect.
tr:first-child:hover{
background-color: white;
color: black;
}
tr:hover{
background-color: #FF0000;
color: #FFFFFF;
}
td{
border: black 1px solid;
text-align: center;
width: 100px;
}
td:hover{
background-color: #AA0000;
border: black 1px solid;
width: 100px;
}
A working version of the code can be found here. As you can see from the example, this small amount of code can make your site a lot more user friendly.


Recent Responses