Repeating Same Color Order in CSS with :nth-child and :nth-of-type

Being a Designer, we probably encountered a situation, where we need to design certain pattern repeatedly in a list. For Example, we have a list of “ n “ items with any shapes. ( like Circle, rectangle ) or something else. The background color of each item is different, in case we style n items with 3 different colors. The color sequence should repeat the same order as follows:

CSS Color Circle

In the above picture, notice that 3 colors repeatedly appears. Generally, we will style the above one, using 3 different classes. (like brown, red, green ) it applicable to some amount of data, while coming to the dynamic values, we need to use the concept “n-th element or child element “.
Lets see this, the above picture are in <li> list in HTML code :

n-child element for this <li> class like as follows :

ul li:nth-child(n) { } , ul li:nth-child(2n) { } , ul li:nth-child(3n) { }
ul li:nth-child(4n) { }, …

If numbering the variable n, we get the values,
If n=0, ul li:nth-child(1), denotes the 1st <li> of ul
n=1, ul li:nth-child(2), the 2st <li> of ul
n=2, ul li:nth-child(3), the 3st <li> of ul
n=3, ul li:nth-child(4), the 5st <li> of ul

This is the basic concept, we need to understand, lets directly go for the main concept.

Example :

In this example, I will display “ n “ number of circles with sequence color pattern using 5 different colors. Let’s see step by step as follows :

1.HTML Code :

2. CSS Code

3.Add common color to the circle :

The webpage will be as follows:

Circle image without color order
Now we need to maintain same order color pattern to the circle, let’s take 5 different colors, which is going to repeat the circle background in same order.
To implement this, use the nth-child concept,

li:nth-child(5n+1) , li:nth-child(5n+2) , li:nth-child(5n+3) , li:nth-child(5n+4) , li:nth-child(5n+5),

for the each value of n , we get the sequence like

li:nth-child (5n+1) (5n+2) (5n+3) (5n+4) (5n+5)
n=0 [5*0]+1=1 [5*0]+2=2 [5*0]+3=3 [5*0]+4=4 [5*0]+5=5
n=1 [5*1]+1=6 [5*1]+2=7 [5*1]+3=8 [5*1]+4=9 [5*1]+5=10
n=2 [5*2]+1=11 [5*2]+2=12 [5*2]+3=13 [5*2]+4=14 [5*2]+5=15
N value will go on, we got the Sequence correctly, now the value of 1,6,11,16… nth-element has the same color background, likewise others…

4. Now add this style to css to reach the goal

The Output is shown as below:

Circle with same order of background
Circle with same order of background

Leave a Reply

Your email address will not be published. Required fields are marked *