admin管理员组

文章数量:1332184

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?

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?

Share edited Mar 3, 2013 at 22:24 animuson 54.8k28 gold badges142 silver badges150 bronze badges asked Nov 25, 2011 at 21:33 JJJollyjimJJJollyjim 6,24719 gold badges58 silver badges79 bronze badges 1
  • Demo: jsfiddle/SXB3e – Jared Farrish Commented Nov 25, 2011 at 21:37
Add a ment  | 

5 Answers 5

Reset to default 5

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.

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.

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.

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;

}

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

本文标签: javascriptSetting the background colour of zebrastriped table rowsStack Overflow