Search code examples
htmlcsscss-selectorspseudo-class

Why are rules for all tables disabled when I add a rule for a particular class of table?


Much better explained with an example:

Fiddle.

I have 2 tables, one of which has a class:

<table>
    <tr>
        <td>111</td>
        <td>222</td>
        <td>333</td>
    </tr>
    <!--  more rows -->
</table>

<table class="letters">
    <tr>
        <td>AAA</td>
        <td>BBB</td>
        <td>CCC</td>
    </tr>
    <!--  more rows -->
</table>

I have 3 rules for table rows. I want the "letters" table to have red rows, and tables with no classes to have blue rows. I also want all rows in all tables to highlight in yellow when the mouse is over them. Hence these rules:

table tr {
    background-color: #33CCFF;
}
table tr:hover {
    background-color: #FAF3B1;
}
table.letters tr {
    background-color: #FF8888;
}

However, the hover rule is only applied to the first table (the one with no class), and not the "letters" table. If I remove the 3rd rule, then, as expected, both tables have blue rows, and the yellow highlighting works.

When I have the 3 rules, they seem to be saying:

  1. make the background color of all table rows blue
  2. make the hover color of all table rows yellow
  3. make the background color of all table rows in tables of class "letters" red (override rule #1 for tables of this class)

So why does the existence of rule #3 make rule #2 stop working? I'm not saying anything about the hover pseudoclass for "letters" table rows, so why doesn't the general rule for all tables apply?


Solution

  • This is actually a case of CSS selectors overriding each other - the third rule overrides the second rule. Just try rearranging them:

    table tr {
        background-color: #33CCFF;
    }
    table.letters tr {
        background-color: #FF8888;
    }
    table tr:hover {
        background-color: #FAF3B1;
    }
    

    Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.

    EDIT: Here's a resource on CSS specificity that may also help you understand the situation better. Note how a class and a pseudo-class both contribute the same specificity to a selector, which is why one is overriding the other.