Search code examples
csscss-specificity

CSS specificity issue with tables


I can't figure out why the following is happening. (I can - and have solved the problem in an unrelated way.)

SUMMARY:

  1. I have a table which the rows have alternating styles. Good.
  2. I wanted to add a color to show "in progress" and "completed".
  3. PROBLEM: The CSS for the alternating row colors keeps trumping my code for "in progress" and "completed".

MORE IN-DEPTH:

The HTML code for the table is:

    <table class="tbl-invoice">
        <tr class="completed">
            <td>9/21/2014</td>
            <td>PAID</td>
            <td class="rep">Bill Bayer</td>
        </tr>

All the styles are in one file.

The CSS for alternating colors:

.tbl-invoice tr:nth-child(odd) td { background-color:#F0F8FF; }

Its specificity is 0 0 2 2.

The CSS for "completed":

.completed { background-color:#e5ffe5; }

The above style trumped it. No problem. So I wrote:

.tbl-invoice tr td .completed { background-color:#e5ffe5; }

which also has a specificity of 0 0 2 2 but is placed BELOW the previous example so this CSS should trump the other.

Not only did it not trump it, but it didn't trump it even when I added body:

body .tbl-invoice tr td .completed { background-color:#e5ffe5; }

Solution

  • How about simplifying your even/odd CSS

    .tbl-invoice tr:nth-child(odd) {background-color:#F0F8FF; }
    .tbl-invoice .completed { background-color:#e5ffe5; }
    

    Here is a similar fiddle