Reputation: 161
How I can set different background colors for only second half of child elements? For example see the following picture:
And my HTML codes:
<div class="items">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
...
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Unfortunately I can't add class to child elements, so I must doing it only with CSS. I tried to use :nth-child
but I did not succeed.
Upvotes: 2
Views: 184
Reputation: 161
Thanks to everyone! I can found a solution:
.items .item:nth-child(10n+6) {background: red;}
.items .item:nth-child(10n+7) {background: red;}
.items .item:nth-child(10n+8) {background: red;}
.items .item:nth-child(10n+9) {background: red;}
.items .item:nth-child(10n+10) {background: red;}
Upvotes: 0
Reputation: 11961
The only way you can do this with pure CSS is if you know the number of child <div class="item">
elements there are. For example, if there are 100 elements, you can select the second 50 using the nth-child()
selector with formula an + b
. b
is the index of the first child element you wish to select, a
is the cycle size and n
is a counter. Here, we choose a = 1
and b = 51
div.items div.item:nth-child(n+51) {
background: yellow;
}
If you don't know the number of child elements, then you have to use JavaScript.
Upvotes: 2