Reputation: 3173
I'm trying to use nth-of-type
to set a gray background for every other .time
and .title
element (odd/even pattern).
<div class="calendar">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background </div>
<div class="title">White Background</div>
</div>
Upvotes: 1
Views: 250
Reputation: 371231
The nth-of-type()
pseudo class doesn't recognize classes. It only cares about elements that are children of the same parent (source).
Moreover, in this case, you don't need to match classes with nth-of-type
.
Based on your HTML structure it looks like you want 2x2 zebra striping.
So, make every element gray, then override every 4th and 4th-1 with white:
div > div {
background-color: lightgray;
}
div > div:nth-child(4n),
div > div:nth-child(4n-1) {
background-color: white;
}
<div class="calendar">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
<div class="time">Gray BG</div>
<div class="title">Gray BG</div>
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
Upvotes: 5
Reputation: 6476
:nth-of-type
matches by the elemnt name, not by the class.
The :nth-of-type(an+b) CSS pseudo-class matches an element that has an+b-1 siblings with the same element name before it in the document tree-type
One way to fix it is to wrap item
and time
in an element, like this:
.appointment:nth-of-type(odd){
background: gray;
}
<div class="calendar">
<div class="appointment">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
</div>
<div class="appointment">
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
<div class="appointment">
<div class="time">Gray Background</div>
<div class="title">Gray Background</div>
</div>
<div class="appointment">
<div class="time">White Background</div>
<div class="title">White Background</div>
</div>
</div>
Upvotes: 0