How to stop colgroup styles being overwritten by tr styles?

2.4k views Asked by At

Hi guys I have a table like that?

<table>

<colgroup>
    <col class="selected">
    <col>
</colgroup>

    <tbody>
      <tr>
          <td>lorem</td>
          <td>lorem</td>
      </tr>
    </tbody>
</table>

and my styles are:

col.selected {
background-color: #f3f3f3; /*for selected column*/
}

table tbody tr:nth-of-type(2n+2){
background-color:#fafafa; /*zebra effect*/
}

all works great however the zerba style owerites col selection style. Any ideas how to avoid that so the selected column will be using style from col rather than nth child ?

3

There are 3 answers

0
Chris Van Opstal On BEST ANSWER

As far as I know, you can't. The best work-around may to be dynamically render some CSS that highlights the correct column. To highlight the second column of a table, for example, you could use:

table tbody tr td:nth-child(2) {
    background-color:red;  
}

Example here: http://jsfiddle.net/ChrisPebble/tbLrv/

4
Chris Felstead On

Your code looks fine other than your col in the html doesn't have a selected class applied. Could this be your problem on the actual page (I relise you've only posted a code sample).

1
Madbreaks On

The problem is that the selector for the zebra background has a higher specificity than the col selector. Either give the col selector a higher specificity, or give the tr selector a lower one (or both). If they're equal, order of rules in your CSS matters.

table colgroup col.selected {
    background-color: #f3f3f3; /*for selected column*/
} /* specificity: 13 */

table tr:nth-of-type(2n+2){
    background-color:#fafafa; /*zebra effect*/
} /* specificity: 12, will be overridden */