tags:

views:

310

answers:

2

Hello,

I've got a table with multiple <tbody> elements.
At a given time, only one <tbody> is displayed, or all of them are displayed.

I currently use this CSS3 code to stripe the table.

table tr:nth-child(even) {
  background: #efefef;
}

When a single <tbody> element is shown, everything is (obviously) fine, but when multiple <tbody> elements are shown the CSS rules apply to each one separately, and each <tbody> has its own "stripes system". Together the stripes may or may not look consistent, depending on the number of rows.

<tbody>
  <tr> [ODD]
  <tr> [EVEN]
  <tr> [ODD]
</tbody>
<tbody>
  <tr> [ODD]
  <tr> [EVEN]
</tbody>
...

Would I absolutely have to use JavaScript (...jQuery) to fix this?

A: 

Yeah, I think you would need script, as there is no nth-grandchild selector that would work relative to the <table>. You'd need script to make it work in older browsers anyway, so probably not a big deal.

var table= document.getElementById('sometable');
for (var i= table.rows.length; i-->0;)
    table.rows[i].className= i%2===0? 'stripe-even' : 'stripe-odd';
bobince
I forgot to mention, I don't care about compatibility. I'm only going to support browsers that support CSS3. Writing a script, especially using jQuery, is not much of a problem. But I really wanted to avoid it, as the table is dynamic and I would have to reapply a lot.
xyz
+1  A: 

If you're using jQuery then use the :even selector, (edited: to handle visibility) like this:

$("table tr:visible:even").addClass("even");​

And a class like this:

.even { background: #efefef; }

Again, that's if you're using jQuery already, if you're not go with a pure javascript solution (including any library for just this is overkill) like bobince posted. Either way I don't see a pure CSS solution here...it's definitely a valid case, but not something that comes up often enough to make it spec-worthy.

Nick Craver
That doesn't solve the question he's trying to have answered. This is just a jQuery version of his problem.
Scott Christopherson
@Scott - It does solve the problem, did you look at the demo? You have to remove and re-apply the class when visibility changes, just like the javascript solution...if you have a simpler non-javascript solution I'd love to see it, but I don't see how that's possible.
Nick Craver
Ah this is correct, I completely misunderstood. I'm trying to change my vote but it's not allowing me unless an edit is made.
Scott Christopherson
@Scott - Updated - added additional handling or visibility as per the question.
Nick Craver
Ah nice, I wouldn't have considered visibility.
Scott Christopherson
Well, I suppose I don't have a choice. :)Thank you.
xyz