inspirednz
inspirednz

Reputation: 5077

How to alternate background colour on DIV rows? (Jquery and/or CSS)

I am customising the CSS for existing HTML output. So I can't change the output, I can only add script (Jquery / Javascript) and custom CSS.

The output produces rows, which form a list of items. This is the structure of the CSS identifiers:

<div>
    <div class="D F">
        <div id=":b" class="G">
        <div id=":c" class="G">
        <div id=":d" class="G">
        <div id=":e" class="G">
        <div id=":f" class="G">
        <div id=":g" class="G">
        <div id=":h" class="G">
    </div>
</div>

The ID of the divs can vary. In some cases it's as shown in my example, in other cases it has :1, :2, :3, etc. Or some other number/letter combination. So that's not something I can rely on for making CSS declarations.

I have tried using the following script, to no effect (found, and modified from here):

$('.D>div:odd').css("background-color", "#ff0000");
$('.D>div:even').css("background-color", "#00ff00");

I also tried the following CSS (found and modified from here):

div.G div:nth-child(even) {background: #CCC;}
div.G div:nth-child(odd) { background: #FFF;}`

But this made every div row grey. They did not alternate.

I created a fiddle here: http://jsfiddle.net/inspirednz/qgb9s8cq/4/

That one includes various other divs that are nested within the divs I am targeting. I have left them in that fiddle, because for some reason (which is not clear to me) the alternate colour I declared actually affects one of the div rows (div.V). But not the others.

Here is another fiddle, with all the nested divs taken out. In this instance the same CSS has no effect at all.

http://jsfiddle.net/inspirednz/qgb9s8cq/3/

Upvotes: 2

Views: 5616

Answers (2)

Almond
Almond

Reputation: 11

Is this what you're looking for? I'm not really familiar with CSS3, but I gave it a shot.

http://jsfiddle.net/qgb9s8cq/6/

div.G:nth-child(even) {
  background: #CCC;
}

div.G:nth-child(odd) {
  background: #FFF;
}

Guess I should have refreshed before posting...

Upvotes: 1

Marko Mackic
Marko Mackic

Reputation: 2333

If I understood correctly what you want,then you want to target your div's not divs inside them :

div.G:nth-child(even) {background: #CCC;}
div.G:nth-child(odd) { background: #FFF;}

It's always preferable to use css over js, because it's hardware accelarated.

Fiddle http://jsfiddle.net/qgb9s8cq/5/

Upvotes: 7

Related Questions