Why doesn't CSS hover work on table rows when

2020-05-25 05:02发布

问题:

I am stuck with this problem so any help would be appreciated. I have a table with several rows. Each cell within the row belongs to a certain class. I use these class names to colour the cells.

Here is one example row from my table:

<tr>
     <td class = "summarypage-odd-column">Theme</td>    <td class = "summarypage-odd-column">Q2 2009</td>   <td class = "summarypage-odd-column">Q1 2009</td>
     <td class = "summarypage-even-column">Theme</td>   <td class = "summarypage-even-column">Q2 2009</td>  <td class = "summarypage-even-column">Q1 2009</td>
     <td class = "summarypage-odd-column">Business Area</td>    <td class = "summarypage-odd-column">Q1 2009</td>   <td class = "summarypage-odd-column">Q1 2008</td>
 </tr>

I would like to highlight each row when the user moves mouse pointer over any cell in that row. So I used the following CSS code to achieve that.

tr:hover {
  background-color: #FFFAF0; color: #000;
}

unfortunately it seems because each table data cell has a class name, the hover does not work. But if I remove the class names from data cells, the hover works.

My question is is there any way I can get the hover thing working for the table row, while still having class names for the table data cells inside the row.

回答1:

Try this:

tr:hover td {
  background-color: #FFFAF0; color: #000;
}

Place this after the existing td style declarations to be safe



回答2:

This does not happen for me. Make sure that you're only adding/removing class names when checking if they have an impact, and make sure that the tds don't have their own background covering up that of the tr.



回答3:

You probably need to use the !important designator to make sure that your hover style overrides the background defined int he class:

tr:hover { 
    background-color: #FFFFAF0 !important;
    color: #000 !important; 
} 

Interestingly, this won't work for IE6 because that browser only applies hover to a tags.



回答4:

The CSS instructions within the classname takes precedence over the <tr> instructions.

To fix this, use td.summarypage-odd-column:hover, td.summarypage-even-column:hover inside your CSS.

Note: If you're using IE6, the :hover only works on links, i.e. a:hover.



回答5:

I think the td background-color overwrites the tr background-color. The solution given by @Nick Craver is the good one.
You must change cells background-color not the row background-color.

tr:hover td {
   ...
}


回答6:

never put space between

tr:hover(space)td

I was giving space hence it was working for me.