Reputation: 5242
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>
Upvotes: 3
Views: 3470
Reputation: 1
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
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