Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SASS Looping Selector

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 :)

like image 674
Paul Avatar asked Feb 15 '23 11:02

Paul


1 Answers

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

like image 117
Russ Ferri Avatar answered Mar 05 '23 02:03

Russ Ferri