josh1978
josh1978

Reputation: 748

CSS Selectors - Determining even/odd children starting with last child

Using CSS only, is there a way to apply and even/odd count starting with the last-child element and going backward to the first-child? I can't use JavaScript for this project; this is for emails generated from a database for Silverpop.

I have a table with several rows that need to alternate background colors. These rows are generated from a database, so they number anywhere from 3 to 6 rows. The last row always needs to be white because immediately following that is a table with a grey background, and I can't have the last row be grey. I'll have a fallback for those email clients that don't support E:nth-of-type.

tr:nth-of-type(even) { grey } would work for 3 rows:

<table>
<tr></tr> (white)
<tr></tr> (grey)
<tr></tr> (white)
</table>

tr:nth-of-type(even) { grey } wouldn't work for 4 rows:

<table>
<tr></tr> (white)
<tr></tr> (grey)
<tr></tr> (white)
<tr></tr> (grey)
</table>

Upvotes: 3

Views: 388

Answers (2)

lc.
lc.

Reputation: 116498

Looking at MDN, :nth-last-of-type seems to be what you want.

tr:nth-last-of-type(even) {background-color: gray}

JS Fiddle Demo

Upvotes: 3

BoltClock
BoltClock

Reputation: 723719

Yes, :nth-last-of-type() exists for this purpose:

tr:nth-last-of-type(even)

However, there isn't a way to provide a fallback for browsers and email clients that don't support this selector with just CSS. You will need to have your application add a class name to the appropriate rows and target by that class instead. If you're unable to modify the application, then you might well be stuck.

Upvotes: 5

Related Questions