I have a parent div, with a varying number of child divs. The child divs will always be within a parent div.
I want to color the child divs in an order, so that the 1st child is blue, the 2nd is purple, and the 3rd is red, and keep repeating blue, purple, red for the rest of the children.
How can I do this with CSS? I would think to use :nth-child(), but I'm not sure how to apply that so that it repeats.
Here's an example of the HTML code (simplified):
<div class="parent">
Parent with 10 children
<!-- IN REALITY, THESE WILL BE CREATED FROM AN ARRAY -->
<div class="child">ONE</div>
<div class="child">TWO</div>
<div class="child">THREE</div>
<div class="child">FOUR</div>
<div class="child">FIVE</div>
<div class="child">SIX</div>
<div class="child">SEVEN</div>
<div class="child">EIGHT</div>
<div class="child">NINE</div>
<div class="child">TEN</div>
</div>
And here is CSS that only works for the first 3 child divs:
.child {
background-color: color-mix(
in srgb,
var(--child-color, rgb(168, 168, 168)) 10%,
transparent
);
color: var(--child-color, rgb(168, 168, 168));
border: 1px solid var(--child-color, rgb(168, 168, 168));
}
/* How do I repeat this so that the children will repeat with backgrounds as blue, purple, red? */
.parent .child:nth-child(1) {
--child-color: oklch(51.01% 0.274 263.83);
}
.parent .child:nth-child(2) {
--child-color: oklch(47.66% 0.246 305.88);
}
.parent .child:nth-child(3) {
--child-color: oklch(61.42% 0.238 15.34);
}
The above code only applies color to the first three divs. I'm not sure how to keep a pattern going with CSS. I'm really hoping to use CSS for this. I guess I could apply different classes to the children based on the index in the loop, but I'd rather use CSS.
I have a stackblitz made for this: https://stackblitz.com/edit/stackblitz-starters-istbgzs4?file=src%2Fglobal_styles.css
You need to use n
multiplier in :nth-child
:
.child {
background-color: color-mix(in srgb,
var(--child-color, rgb(168, 168, 168)) 10%,
transparent);
color: var(--child-color, rgb(168, 168, 168));
border: 1px solid var(--child-color, rgb(168, 168, 168));
}
/* How do I repeat this so that the children will repeat with backgrounds as blue, purple, red? */
.parent .child:nth-child(3n+1) {
--child-color: oklch(51.01% 0.274 263.83);
}
.parent .child:nth-child(3n+2) {
--child-color: oklch(47.66% 0.246 305.88);
}
.parent .child:nth-child(3n) {
--child-color: oklch(61.42% 0.238 15.34);
}
<div class="parent">
Parent with 10 children
<!-- IN REALITY, THESE WILL BE CREATED FROM AN ARRAY -->
<div class="child">ONE</div>
<div class="child">TWO</div>
<div class="child">THREE</div>
<div class="child">FOUR</div>
<div class="child">FIVE</div>
<div class="child">SIX</div>
<div class="child">SEVEN</div>
<div class="child">EIGHT</div>
<div class="child">NINE</div>
<div class="child">TEN</div>
</div>