Search code examples
sass

How to generate multiple values of CSS property using SCSS?


How to generate the following CSS in SCSS for given count n?

background-image:
  linear-gradient(#FFF 1, transparent 0),
  linear-gradient(#FFF 2, transparent 0),
  ...
  linear-gradient(#FFF n, transparent 0);

background-position:
  0px center,
  1px center,
  ...
  npx center;

(This is just a simple useless example for demonstration.)


Solution

  • You can write a function containing a for-loop to build up a list by appending a new comma separated value in each iteration.

    @function gradient-n($n){
      $sequence: ();
      @for $i from 1 through $n {
        $new: linear-gradient(#FFF $i, transparent 0);
        $sequence: append($sequence, $new, comma);
      }
      @return $sequence;
    }
    
    
    .foo {
        background-image: gradient-n(5);
    }