SASS Looping Selector

include, loops, sass, selector

Solution

You can use a `for` loop to generate the selector chain and then inject it into a rule with interpolation:

@mixin depth($depth: 1) {
  $chain: '';
  @for $i from 0 to $depth {
    $chain: $chain + ' > ul > li';
  }

  & #{$chain} {
    @content;
  }
}

example | gist

Problem

I have got this repetitive selector as shown below: ``` // Level 1 .wrap > ul > li { background: green; } // Level 2 .wrap > ul > li > ul > li { background: orange; } // Level 3 .wrap > ul > li > ul > li > ul > li { background: red; } // Level 4 .wrap > ul > li > ul > li > ul > li > ul > li { background: light-red; } // Level 5 .wrap > ul > li > ul > li > ul > li > ul > li > ul > li{ background: salmon; } ``` Is there a way I can create a sass function so I can just specify the depth and color like this ``` **for example** @include depth(5) { background: salmon }) ``` I would appreciate your help :)

Original source