Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override row color on a single row inside a table with alternating row colors

Tags:

html

css

I've got a table with CSS3 alternating row styles but I need to override the styling for a few rows.

Here is the CSS for the table:

table.primary tr:nth-child(odd) {
    background-color: #e5e5e5;
}
table.primary tr:nth-child(even) {
    background-color: #ededed;
}

I need to override some rows with a very different background-color (and other formatting), and I was hoping to just add a class= to the individual rows, but it appears that this does not override the above CSS.

e.g.

<table class="primary">
    <tr><td>one</td></tr>
    <tr class="new"><td>two</td></tr>
    <tr><td>three</td></tr>
</table>

Alternatively I'll need to skip CSS3 and just use a class="row1", class="row2", class="new" instead.

Any suggestions on how to override the nth-child with a class?

like image 666
hyarion Avatar asked Nov 15 '11 12:11

hyarion


People also ask

How would you style table rows to have alternating background color?

You can use the nth child selector in CSS3 to very simply create tables with alternating row colors.

How do I alternate row colors in Excel by group?

Switch to the Home tab > Styles group and click Conditional Formatting > New Rule... Then click the Format button, switch to the Fill tab and select the background color that you want to use for the banded rows. At this point, the selected color will appear under Sample. If you are happy with the color, click OK.

How do you color a single row of a table?

where N (the table's ID), and X (the number of the row) need to be adjusted to your table! #ff0000 is the HEX color code of the desired color, in this case red. You can change both the text color (via the color property) and the background color (via the background-color property).


2 Answers

As classes and pseudo-classes share the same specificity, it should be enough to define the .new style rule after the :nth-child() rules like this, assuming a single class is to overidde all other styles:

table.primary tr:nth-child(odd) {
    background-color: #e5e5e5;
}
table.primary tr:nth-child(even) {
    background-color: #ededed;
}
table.primary tr.new {
    background-color: #ffc;
}

jsFiddle demo

like image 154
BoltClock Avatar answered Oct 06 '22 23:10

BoltClock


try this

table.primary tr.new:nth-child(odd) {
background-color: #ff0000;
}
table.primary tr.new:nth-child(even) {
background-color: #000000;
}
like image 42
Swap Avatar answered Oct 06 '22 23:10

Swap