SASS serial switch

I have this repeating 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 to create a sass function, so I can just specify the depth and color as follows

 **for example** 
 @include depth(5) { background: salmon })

I would be grateful for your help :)

+4
source share
1 answer

You can use a loop forto generate a chain of selectors, 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

+8
source

All Articles