leonard0
leonard0

Reputation: 143

sass mixin pass argument as css variable

I have a mixin to generate some grid classes as follows:

@mixin grid-columns($columns) {
  @for $i from 1 through $columns {
    .grid-col-#{$i} {
      grid-column: span #{$i};
    }
  }
}

I also declared a css variable at :root { --grid-columns: 12; }

i tried passing the --grid-columns variable to mixin as a variable as such

@include grid-columns(var(--grid-columns));

However, this is not working and i get the following error:

Error: var(--grid-columns) is not an integer. on line 26:23 of assets/scss/_base.scss, in mixin grid-columns from line 26:10 of assets/scss/_base.scss from line 3:9 of /stdin

@include grid-columns(var(--grid-columns));

Can anyone explain why this is not working please? I couldn't find anything online where it specifies if css variables are/are not allowed to be passed in as arguments to sass mixins, but i suspect they are not allowed?

Upvotes: 1

Views: 2417

Answers (2)

userCirc
userCirc

Reputation: 1

The issue probably lies in Sass compiling before the CSS Custom property. You can use interpolation to evaluate the variable beforehand.

@mixin style($color: #{var(--my-color)}) {
    color: $color;
}

https://sass-lang.com/documentation/interpolation/

Upvotes: 0

David Bambušek
David Bambušek

Reputation: 136

SCSS does not have access to the passed CSS variable's value. You are passing only the reference to the CSS variable that is evaluated once you open the page in browser.

Therefore by doing this:

@include grid-columns(var(--grid-columns));

You are not passing the value 12 but only a reference to the --grid-columns CSS variable.

In the mixin

@for $i from 1 through $columns

SCSS is then confused because after through, there should be an integer, but it got CSS variable reference, that it does not understand and fails.

Upvotes: 1

Related Questions