Paul
Paul

Reputation: 1220

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

Upvotes: 4

Views: 520

Answers (1)

Russ Ferri
Russ Ferri

Reputation: 6589

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

Upvotes: 8

Related Questions