tags:

views:

54

answers:

4

Lets say i have 50 element grid. If its wide list it is easy for readers if i color odd and even div differently. Now lets say i want to do this and color code every 5th div. Is there a way to choose which css to apply based on a number? like instead of

<div class="odd">blah</div>
<div class="even">blah</div>
<div class="odd">blah</div>
<div class="even">blah</div>
<div class="fifthOdd">blah</div>
...
<div class="fifthEven">blah</div>

to do something like

<div class="1">blah</div>
<div class="2">blah</div>
...
<div class="5">blah</div>
...
<div class="10">blah</div>

and allow whoever writing the css to choose how the color scheme works based on their index?

A: 

CSS has no way of selecting based on a class name that changes like that.

There are various nth-selectors proposed for CSS 3, but browser support is currently weak.

David Dorward
+6  A: 

Yes, with nth-child. Note that nth-child doesn't work in IE, but it is a valid jQuery selector, so you can either use this with modern browsers and pure CSS, or with all browsers and a bit of presentational JavaScript.

Skilldrick
Hmm, small problem. Its being applied to ALL child's. I only want it to be count and apply to the first depth (count all childs but not grandchildren). Any ideas for a solution?
acidzombie24
You could use the direct descendent `>` operator. So `div > div:nth-child(2n)` or something like that. This is valid IE7+.
Skilldrick
I tried for 15 mins and i cant figure it out. Would you mind giving me your email/emailing me so i can send a html file +css? if your busy then its ok.
acidzombie24
Put it into http://jsfiddle.net/ and post a link...
Skilldrick
Hmmm. Sorry, I'm a bit lost now, and I don't really have time I'm afraid. I'm sure it's something to do with `>`, but might be worth a separate question (e.g. "How to use nth-child with only direct children")
Skilldrick
k thanks for the solution on this answer!
acidzombie24
A: 

Assuming you can actually use numbers as css classnames, the css could look like

div.1, div.3, div.5, div.7
{
// Odd Style here
}

div.2, div.4, div.6, div.8
{
// Even Style here
}

Not that pretty, but flexible enough to do what you ask.

Jens
You shouldn't use numbers for classnames though... But you could say `class="no1"` etc.
Skilldrick
+2  A: 

You can use jQuery to select all even or odd nodes, and then apply a css class to them.

http://api.jquery.com/nth-child-selector/

$('#parentDiv:nth-child(even)').addClass('evenDivs');
$('#parentDiv:nth-child(odd)').addClass('oddDivs');
danilo