DEV Community

Cover image for Generate Custom Properties (CSS Variables) using SASS
Kunal Tanwar
Kunal Tanwar

Posted on • Edited on

Generate Custom Properties (CSS Variables) using SASS

We've all encountered situations where we need to create variables with different units for various purposes, such as margin, padding, or border-radius. In CSS, this typically involves hard-coding each unit individually. However, there's a more efficient way to handle this and save time using SCSS.

To create a range of pixel units using a @for loop in SCSS, you can do the following:

:root {
  @for $i from 1 through 8 {
    --unit-#{$i}: #{$i}px;
  }
}
Enter fullscreen mode Exit fullscreen mode

This will generate the following CSS output:

:root {
  --unit-1: 1px;
  --unit-2: 2px;
  --unit-3: 3px;
  --unit-4: 4px;
  /* ... up to --unit-8 */
}
Enter fullscreen mode Exit fullscreen mode

If you want to convert these pixel units to rem, you can use a helper function:

@use 'sass:math';

@function rem($value) {
  @return math.div($value, 16) * 1rem;
}
Enter fullscreen mode Exit fullscreen mode

Remember to include @use 'sass:math'; as the first line in your SCSS file.

Then, apply the function like this:

:root {
  @for $i from 1 through 4 {
    --unit-#{$i}: #{rem($i)};
  }
}
Enter fullscreen mode Exit fullscreen mode

This will result in the following CSS output:

:root {
  --unit-1: 0.0625rem;
  --unit-2: 0.125rem;
  --unit-3: 0.1875rem;
  --unit-4: 0.25rem;
}
Enter fullscreen mode Exit fullscreen mode

To take it further and use CSS variables within variables, you can do the following:

:root {
  @for $i from 0 through 4 {
    @if $i == 0 {
      --base: rem(1);
    } @else {
      --unit-#{$i * 2}: calc(var(--base) * #{$i * 2});
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

This will result in the following CSS output:

:root {
  --base: 0.0625rem;
  --unit-2: calc(var(--base) * 2);
  --unit-4: calc(var(--base) * 4);
  --unit-6: calc(var(--base) * 6);
  --unit-8: calc(var(--base) * 8);
}
Enter fullscreen mode Exit fullscreen mode

You can customize the base value and utilize the helper function as needed for more flexibility.

Thats all From Me

Top comments (0)