JJJollyjim
JJJollyjim

Reputation: 6217

Setting the background colour of zebra-striped table rows

I am using:

tr:nth-child(2n+1) {
  background-color: #DDDDDD;
}

To zebra-stripe a table. I have the class:

.redbg {
  background-color: #FF6666;
}

And am using:

$(this).parent().parent().addClass("redbg");

To use JQuery to change the background colour of the rows when I need to.

Unfortunatly, it only works on the non-2n+1 rows. How do I recolour the #DDDDDD rows?

Upvotes: 3

Views: 1787

Answers (5)

animuson
animuson

Reputation: 54729

Simply change the "redbg" class to add the tr to the front:

tr.redbg {
    background-color: #FF6666;
}

This occurs because tr:nth-child(2n+1) is more specific than .redbg so it overrides the background color no matter what. Changing it to tr.redbg makes it just as specific so the "redbg" class will override the :nth-child() selector.

See the jsFiddle

Note for future reference: The tr.redbg selector has to be defined after the tr:nth-child(2n+1) selector in order for it to override the background color.

Upvotes: 5

Adam Rackis
Adam Rackis

Reputation: 83356

Don't use !important (as another answer suggests)

Instead, make your selector more specific. Add add something like

table tr.redbg { background-color: #FF6666; }

Here's a great link on calculating CSS specificity.

Upvotes: 2

Ilia G
Ilia G

Reputation: 10211

Something about tr:nth-child(2n+1) taking priority because it is more specific selector.

Change the other one to

tr.redbg {
  background-color: #FF6666;
}

and it shoudl work

Upvotes: 1

nickf
nickf

Reputation: 546035

It seems like that might have something to do with the rules of CSS specificity.

Try changing your selector to tr.redbg and see if that works.

Upvotes: 2

Alex KeySmith
Alex KeySmith

Reputation: 17101

I think you need to make your redbg class more explicit than the nth child to override it.

Maybe something like (though I haven't tested it, but should get you started):

.redbg, tr.redbg:nth-child(2n+1)
{
background-color: #FF6666;

}

Upvotes: 1

Related Questions