Use nth-child value as a SASS variable
47,772
Solution 1
I don't think there's a way to do exactly that. But you can use @for
directive to loop through a known number of elements:
$elements: 15;
@for $i from 0 to $elements {
div:nth-child(#{$i + 1}) {
background: rgb($i, $i, $i);
}
}
Solution 2
You could use a mixin like this:
@mixin child($n) {
&:nth-child(#{$n}){
background-color:rgb($n,$n,$n);
}
}
div{
@include child(2);
}
The compiled css looks like:
div:nth-child(2) {
background-color: #020202;
}
See an example here
Related videos on Youtube
Comments
-
zessx almost 2 years
Is there any way to use the
nth-child
value as a SASS variable ?Examples of use :
div:nth-child(n) { content: '#{$n}' }
div:nth-child(n) { background: rgb(#{$n}, #{$n}, #{$n}); }
-
zessx over 10 yearsThanks, but the goal is to avoid multiple similar lines.
-
zessx over 10 yearsThat's what I'm doing today, would be nice to find a way to do this on an unknown number of elements.
-
ahnbizcad over 9 yearsis there a way to set
$elements
dynamically according to how many elements there are in your generated DOM? -
myajouri over 9 years@gwho you can't do that since CSS doesn't know about what's in the DOM.
-
ahnbizcad over 9 yearsI worked around this by simply assigning unique id's and referencing those.
-
ahnbizcad over 9 yearsStill dependent on explicit arguments passed in, but still better than completely manual! Thanks!
-
Wiseman about 9 yearsNice snippet, thanks a lot. But for me worked normally only when I've replaced "from 0 to $elements" => "from 1 to $elements + 1" and "rgb(#{$i},..." -> "rgb($i,...". Not sure if my version of sass has to do with the latter issue.
-
fontophilic about 9 years@ahnbizcad, there does exist a convoluted way to get DOM information set as SASS vars, if you compile your sass server side. Which is a terrible idea. viget.com/extend/…
-
Winnemucca over 6 yearscan you do this in a media query?
-
Josh Harrison about 6 yearsNeeded to use
:nth-child(#{$i + 1})
asnth-child
starts at 1, not 0 -
Ernesto almost 6 yearsyou saved my life i needed to add the column with the number of child for a project :)