Search code examples
csssass

Repeated Parent Patterns in scss


Is there a way to simplify such structure

$padding: 1rem;
ul a {
  padding-left: 0 * $padding;
}

ul ul a {
  padding-left: 1 * $padding;
}
ul ul ul a {
  padding-left: 2 * $padding;
}
ul ul ul ul a {
  padding-left: 3 * $padding;
}

That doesn't really feel right...

the only alternative i can comeup with is one below, but it also not really plesant to eye.

ul {
  a {
    padding-left: 0 * $padding;
    ul & {
      padding-left: 1 * $padding;
      ul & {
        padding-left: 2 * $padding;
        ul & {
          padding-left: 3 * $padding;
        }
      }
    }
  }
}

Solution

  • A simple nested for loop would do the job for you.

    Something like:

    $padding: 1rem;
    
    @for $i from 0 through 3 {
      $selector: 'ul';
      
      @for $j from 1 through $i {
        $selector: $selector + ' ul';
      }
    
      #{$selector} a {
        padding-left: $i * $padding;
      }
    }
    

    Explanation of above code:

    • Outer @for loop iterates 0 through 3 times, for nested ul elements.
    • Inner @for loop iterates 1 through the current iteration of the outer loop, representing the currently iterating ul elements.
    • Finally, we can loop through the levels and build the selector string $selector by appending ul to it after which we can use the interpolation #{} to insert the selector string in the style rule.

    DEMO