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

Share:
47,772

Related videos on Youtube

zessx
Author by

zessx

➜ smarchal.com ➜ blog.smarchal.com

Updated on July 09, 2022

Comments

  • zessx
    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
    zessx over 10 years
    Thanks, but the goal is to avoid multiple similar lines.
  • zessx
    zessx over 10 years
    That's what I'm doing today, would be nice to find a way to do this on an unknown number of elements.
  • ahnbizcad
    ahnbizcad over 9 years
    is there a way to set $elements dynamically according to how many elements there are in your generated DOM?
  • myajouri
    myajouri over 9 years
    @gwho you can't do that since CSS doesn't know about what's in the DOM.
  • ahnbizcad
    ahnbizcad over 9 years
    I worked around this by simply assigning unique id's and referencing those.
  • ahnbizcad
    ahnbizcad over 9 years
    Still dependent on explicit arguments passed in, but still better than completely manual! Thanks!
  • Wiseman
    Wiseman about 9 years
    Nice 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
    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
    Winnemucca over 6 years
    can you do this in a media query?
  • Josh Harrison
    Josh Harrison about 6 years
    Needed to use :nth-child(#{$i + 1}) as nth-child starts at 1, not 0
  • Ernesto
    Ernesto almost 6 years
    you saved my life i needed to add the column with the number of child for a project :)