Open In App

How to use a sass variable in nth child class ?

SASS is one of the most popular CSS extension languages which provides superpower to the normal CSS. The nth-child() class is a pseudo-class, when some HTML element has more than two elements of the same kind then we can use the nth-child class pseudo-class to provide styling to those elements without defining a separate class.

For example, if a div has 5 <p> element then we can use nth-child(), For this article, we will use the sass variable in an nth-child class.



Syntax:

<css selector> : nth-child(an + b){ css properties };

 



Parameters:

Example 1: In this example, we will add 6 <p> elements in the <div> and create a variable of the name text-color and use it in the nth-child(2n) class to change the colors of the text which will change the colors of the even number of text from the list.

style.scss




$text-color : green;
  
p:nth-child(2n){
    color: $text-color;
}

Compiled CSS file.

style.css




p:nth-child(2n) {
    color: green;
}

Index.html




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Sass variable in nth-child class</title>
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <h2 style="color: green;">GeeksforGeeks</h2>
  
    <div class="main">
        <p class="text1">1. GeeksforGeeks</p>
        <p class="text2">2. GeeksforGeeks</p>
        <p class="text3">3. GeeksforGeeks</p>
        <p class="text4">4. GeeksforGeeks</p>
        <p class="text5">5. GeeksforGeeks</p>
        <p class="text6">6. GeeksforGeeks</p>
    </div>
</body>
</html>

Output:

 

Example 2: In this example, we will use the two different sass variables for both the odd and even number of elements in the nth child class, green color for even elements and red color for odd elements.

style.scss




$even-text-color : green;
$odd-text-color : red;
  
p:nth-child(2n){
    color: $even-text-color
p:nth-child(2n-1){
    color: $odd-text-color;
}

Complied CSS file

style.css




p:nth-child(2n) {
    color: green;
}
  
p:nth-child(2n-1) {
    color: red;
}

Index.html




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Sass variable in nth-child class</title>
    <link rel="stylesheet" href="style.css">
</head>
  
<body>
    <h2 style="color: green;">GeeksforGeeks</h2>
  
    <div class="main">
        <p class="text1">1. GeeksforGeeks</p>
        <p class="text2">2. GeeksforGeeks</p>
        <p class="text3">3. GeeksforGeeks</p>
        <p class="text4">4. GeeksforGeeks</p>
        <p class="text5">5. GeeksforGeeks</p>
        <p class="text6">6. GeeksforGeeks</p>
    </div>
</body>
</html>

Output: 

 


Article Tags :