We know that we can use nth-child
to apply specific style targeted elements. For example, to style the .col
who is a second child to its parent, we can use the .col:nth-child(2)
syntax.
<style>
.flex { display: flex; flex-wrap: wrap; }
.col { width: 25%; }
.col:nth-child(2) { color: red; }
</style>
<div class="flex">
<div class="col">Col 1</div>
<div class="col">Col 2</div> <!-- This will be red color -->
<div class="col">Col 3</div>
<div class="col">Col 4</div>
<div class="col">Col 5</div>
<div class="col">Col 6</div>
<div class="col">Col 7</div>
<div class="col">Col 8</div>
</div>
However, nth-child
can achieve more. It also accepts keywords and formula as its parameter.
Even and Odd
Using back the same example, we can style the even number children as red by using .col:nth-child(even)
.
<style>
...
.col:nth-child(even) { color: red; }
</style>
<div class="flex">
<div class="col">Col 1</div>
<div class="col">Col 2</div> <!-- This will be red color -->
<div class="col">Col 3</div>
<div class="col">Col 4</div> <!-- This will be red color -->
</div>
Formula
What if we need to style every 4th elements, for example, the 4th, 8th, 12th and 4(N)th elements?
nth-child
also accepts a formula in the form of nth-child(an + b)
where a
is the cycle size and n
is the counter (starts from 0).
To achieve the example mentioned, you can use nth-child(4n)
.
<style>
...
.col:nth-child(4n) { color: red; }
</style>
<div class="flex">
<div class="col">Col 1</div>
<div class="col">Col 2</div>
<div class="col">Col 3</div>
<div class="col">Col 4</div> <!-- This will be red color -->
<div class="col">Col 5</div>
<div class="col">Col 6</div>
<div class="col">Col 7</div>
<div class="col">Col 8</div> <!-- This will be red color -->
</div>