javascript - Setting the background colour of zebra-striped table rows - Stack Overflow

I am using:tr:nth-child(2n+1) {background-color: #DDDDDD;}To zebra-stripe a table. I have the class:.r

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742260795a4410866.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信