CosmicDrawers
CosmicDrawers

Reputation: 43

Alternate more than 2 background colors with CSS or JS

I currently have several <section> elements that repeat themselves and I want to assign a 5 different alternating background colors.

Right now I'm using :nth-of-type(#n) but I'm almost positive that I'm not using it right and some weird behavior is happening where one of the colors does not repeat through the cycle.

This is an example code:

HTML

<section>
    <article>This is A1</article>
</section>
<section>
    <article>This is A2</article>
</section>
<section>
    <article>This is A3</article>
</section>
<section>
    <article>This is A4</article>
</section>
<section>
    <article>This is A5</article>
</section>

CSS

section:nth-of-type(1n) {
    background-color: red;
}

section:nth-of-type(2n) {
    background-color: orange;
}

section:nth-of-type(3n) {
    background-color: blue;
}

section:nth-of-type(4n) {
    background-color: green;
}

section:nth-of-type(5n) {
    background-color: gray;
}

Is there a more efficient way of doing this? I would prefer to keep this within the realms of CSS but I do not mind adding JS instructions.

Here's the JFiddle demo.

Many thanks!

Upvotes: 2

Views: 2159

Answers (1)

Stephen Callender
Stephen Callender

Reputation: 538

You're close. Just change your nth-of-type counting to the following.

section:nth-of-type(5n+1) {
    background-color: red;
}

section:nth-of-type(5n+2) {
    background-color: orange;
}

section:nth-of-type(5n+3) {
    background-color: blue;
}

section:nth-of-type(5n+4) {
    background-color: green;
}

section:nth-of-type(5n+5) {
    background-color: gray;
}

Here's the JFiddle.

Upvotes: 3

Related Questions