Rap
Rap

Reputation: 7292

CSS selector precedence - why is td higher than a pseudo-selector?

Look at this fiddle: http://jsfiddle.net/czz2ejfw/1

Style for my table:

td {
    color: #669;
}
tbody tr:hover {
    color: red;
}

The text color should be red when we hover. In fact, if you look at developer tools you see that red should be applied. But incredibly, it displays as #669. WTH?

This is consistent across Firefox, Chrome, Safari, and Opera.

Upvotes: 1

Views: 896

Answers (4)

Carlos Calla
Carlos Calla

Reputation: 6706

Update that part of your CSS to this and it will work:

tbody tr:hover {
    background-color: yellow;
}
tbody tr:hover td{
    color: red;
}

Red is higher priority in your version because it is specific for td the tbody tr is not that specific

Upvotes: 0

user2908232
user2908232

Reputation: 451

As actually already said in a comment, the td is a child of the tr, so although the background of the tr changes, if you can't see it anywhere because none of the td's are transparent you won't get anywhere. The correct solution thus is to either make the td's transparent (default) and instead style the tr's always, or use tr:hover td{} to override the styles of the td instead of styling the tr.

Upvotes: 1

Quentin
Quentin

Reputation: 943579

It isn't more specific. It matches a different element.

td { color: #669; } overrides the default stylesheet (which is probably something like td { color: inherit; }) because author stylesheets override browser stylesheets.

If you want to match the td when the tr is hovered, then you need to mention the td in the selector (e.g. with a descendant combinator).

tbody tr:hover td {}

Upvotes: 5

Dan
Dan

Reputation: 9468

<tr> is getting the color:red; but there is nothing there to be styled red.

Instead you would need to do this, which applies red to all <td> cells that are children of the parent <tr>:

tbody tr:hover {
    background-color: yellow;
}

tbody tr:hover td {
    color: red;
}

JS Fiddle Demo

Upvotes: 1

Related Questions