Iterating over nth-children w/ Sass
Let's say we have a number of nth-children we want to apply a varied transition delay to. This could be done by targeting each element individually and manually setting the transition delay, but there is a much more efficient way. By using the power of a Sass @for
loop we can dynamically target each element and apply varying properties. Below we will go over the code involved and look at the output.
The HTML
<ul>
<li>Dashboard</li>
<li>Favorites</li>
<li>Profile</li>
<li>Settings</li>
</ul>
A simple unordered list, we are going to be targeting the <li>
elements.
The Mixin
@mixin transition {
@for $i from 1 through 4 {
&:nth-child(#{$i}) {
transition: all .2s #{$i * .1}s ease-in;
}
}
This is the fun part! Essentially, what is happening is we are looping from 1 through 4 and each time passing in our $i
variable to the nth-child()
selector. For each iteration of the loop we also assign the transition delay to $i * .1
effectively giving us a different value for each child.
The SCSS
li {
@include transition;
}
Here we are simply including our mixin on the li
selector.
The CSS Output
li:nth-child(1) {
transition: all 0.2s 0.1s ease-in;
}
li:nth-child(2) {
transition: all 0.2s 0.2s ease-in;
}
li:nth-child(3) {
transition: all 0.2s 0.3s ease-in;
}
li:nth-child(4) {
transition: all 0.2s 0.4s ease-in;
}
Looking at this output should give you a pretty solid handle on what has actually happened when we included the mixin.
Click here to see it in action
Written by Cameron White
Related protips
3 Responses
Very clear and easy to understand! Thanks Cam!
This did not work for me. The mixin definition is invalid that way.
What worked for me
scss
li {
@for $i from 1 through 4 {
&:nth-child(#{$i}) {
transition: all .2s #{$i * .1}s ease-in;
}
}
}
Hi, i have a question, i know that i gotta interpolate a variable when it will be the parameter of the nth-child pseudoclass...but I don't understand why, why can't i use the variable directly like parameter if the value is a number ?, why i gotta interpolate it to work ?...sorry for my bad english, i'm from Venezuela and i learned with playstation .___. , I hope your answer, I'm a beginner and I'm studying on my own