Domanda

I have a table with alternate row background-color:

tr:nth-child(even) {background: #FFF}
tr:nth-child(odd) {background: #f4f4f4}

The table is comprised of two types of cells, ".main" and ".sub".

I would like the background-color to alternate every other ".main", while all ".sub" rows get the color of the previous ".main".

It would be great if the solution were all CSS, but open to jquery if it's really the best way to go.

Any ideas?

<table>
    <tr id='1' class='main'><td></td></tr>
    <tr id='2' class='main'><td></td></tr>
    <tr id='3' class='main'><td></td></tr>
    <tr id='4' class='main'><td></td></tr>
    <tr id='5' class='main'><td></td></tr>
    <tr id='6' class='sub'><td></td></tr>
    <tr id='7' class='main'><td></td></tr>
    <tr id='8' class='main'><td></td></tr>
    <tr id='9' class='sub'><td></td></tr>
    <tr id='10' class='sub'><td></td></tr>
    <tr id='11' class='main'><td></td></tr>
</table>

rows 1,3,5,8 should be #f4f4f4

rows 2,4,7,11 should be #fffff

and each .sub row should be the same color as the preceding .main row.

(these tables are dynamically generated, so their placement will vary)

EDIT: here is the jsfiddle of my failed first attempt with jQuery http://jsfiddle.net/xjDZm/

È stato utile?

Soluzione

I don't think this is possible with pure CSS, as you seem to need to style the odd rows of .main, not odd rows and .main, and :nth-child can not do that (you can't use (tr.main):nth-child(odd), not to mention your requirement with .sub is even more complicate).

So here's a jQuery solution:

$("tr.main").filter(":even").css("background-color","#CCC");//change to #F4F4F4
$("tr.main").filter(":odd").css("background-color","#FFF");
$("tr.sub").each(function(i,e){
    $(this).css("background-color",$(this).prev().css("background-color"));
});

http://jsfiddle.net/xjDZm/1/

Sorry that I don't use jQuery, so I'm not sure if there's any better way to code. I just look up the API document to find methods that work.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top