pglaz
pglaz

Reputation: 35

CSS tables: changing background on hover, including alternative rows

I have created a sample page with a table. Should the page get deleted in the future, here's the code on Pastebin.

I want to highlight table rows on hover. It works for normal tr but it doesn't work for tr.alt (odd rows).

Code for highlighting:

tr:hover,tr.alt:hover
{
background: #f7dcdf;
}

Code for making odd rows different colour:

tr.alt td
{
background: #daecf5;
}

Any ideas how this could be fixed?

Upvotes: 3

Views: 16473

Answers (2)

Pevara
Pevara

Reputation: 14310

The problem is that tr.alt td is more specific then tr.alt:hover according to css cascading rules.

The easy way would be to make sure that the :hover rule becomes more specific then the .alt rule. This can be done by changing tr.alt td to tr.alt

As a sidenote, are you aware that you do not need the .alt class to target the odd rows? There is a very usefull :nth-child() pseudo class that can take care of that for you. You can read all about it here: http://css-tricks.com/how-nth-child-works/

I took the liberty to apply this to your sample: http://jsfiddle.net/3tV9b/
Note that all I did was change tr.alt td to tr:nth-child(2n+1) and removed all selectors that had the .alt class.

The big advantage of this technique is that you do not need to bother about maintaining the HTML, you can just add and remove rows as you wish, and the alternating color should keep working.

Disadvantage is (off course) the support in IE, but I think this is not really a loss of functionality, and well within the boundaries of graceful degrade.

Upvotes: 2

omma2289
omma2289

Reputation: 54619

Make sure the rule for the hovering effect is below the .alt color as this overwrites previous rules or add !important

tr:hover,tr.alt:hover
{
    background: #f7dcdf!important;
}

Also note you are applying the background color for the .alt rows to the cells (td's), this color will appear "in front" of the tr background so change your rules so both are for cells or for the whole rows

Upvotes: 10

Related Questions