MortenMoulder
MortenMoulder

Reputation: 6648

Change background color on hover in table with preset background color

I am trying to change the background color of my whole tbody using CSS and :hover. When a background is already set, I cannot make the hover background change. I simply cannot. I even tried with !impotant but without luck.

<table border="1">
    <tbody>
    <tr>
        <th>Testing</th>
        <td>Some stuff</td>
    </tr>
    <tr>
        <th>Testing</th>
        <td>Second more stuff</td>
    </tr>
    </tbody>
</table>

My CSS

th {
    background: red;
}
tbody:hover {
    background: blue !important;
}

http://jsfiddle.net/W4cJh/1/

As you can see, the hover works fine if the background has not been set. Remove the background: red from the th-tag, to see that it works without a preset color.

Upvotes: 0

Views: 613

Answers (2)

Arbel
Arbel

Reputation: 30989

This will do the work for you, no need for !important:

th {
    background: red;
}
tbody:hover,
tbody:hover th {
    background: blue;
}

Demo: http://jsfiddle.net/W4cJh/4/

Upvotes: 2

dthree
dthree

Reputation: 20730

That's because the TH is a child of the table, and so is technically on top of it. By setting the TABLE background to blue, it does not override the TH background.

To fix this, add this:

tbody:hover th {
  background: blue;
}

(and you can skip the !importants. Those are bad practice.)

Example fiddle is here.

Upvotes: 1

Related Questions