MrProgram
MrProgram

Reputation: 5242

Make every second div different background color

I using CSS to give every second div a different background color, but somehow I get both when using (odd) and no one when using (even), how is that?

.hoverDiv:nth-child(odd) {
     background: red;
}
.hoverDiv:hover {
    background: #696969;
    cursor: pointer;
}

<div class="modal-body">
     <div>
            <div class="hoverDiv">
                <h2>Number 1</h2>
            </div>
        </div>
        <div>
            <div  class="hoverDiv">
                <h2>Number 2</h2>
          </div>
     </div>
</div>

http://jsfiddle.net/j9S8v/87/

Upvotes: 3

Views: 3470

Answers (2)

You have just to remove the outer div... see the code and use nth-child(2n) or use nth-child(even) both will work correctly

.hoverDiv:nth-child(2n) {
    background: red;
}
.hoverDiv:hover {
     background: #696969;
     cursor: pointer;
    }
<div class="modal-body">
       <div class="hoverDiv">
          <h2>Number 1</h2>
        </div>
        <div  class="hoverDiv">
            <h2>Number 2</h2>
        </div>
</div>

Upvotes: 0

Kris
Kris

Reputation: 41847

It's because your nesting is different from your css selector. In your html, the hoverDiv does not have any (element) siblings.

.hoverDiv:nth-child(odd) {
      background: red;
}
.hoverDiv:hover {
     background: #696969;
     cursor: pointer;
}

<div class="modal-body">
    <div class="hoverDiv">
        <h2>Number 1</h2>
    </div>
    <div  class="hoverDiv">
        <h2>Number 2</h2>
    </div>
</div>

Upvotes: 9

Related Questions