How to Assign CSS Variable Value to scss Variable or Expression

Viewed 7220

I'm trying to build my own tiny scalable grid in CSS / scss. So far I found this decision:

:root {
  --page-width: 1170px;
  --gutter: 15px;
  --columns: 12;
}

.wrapper {
  max-width: var(--page-width);
  margin-right: auto;
  margin-left: auto;
  padding-left: var(--gutter);
  padding-right: var(--gutter);
}

.row {
  margin-left: calc(-1 * var(--gutter));
  margin-right: calc(-1 * var(--gutter));
}

.col {
  display: block;
  margin-left: var(--gutter);
  margin-right: var(--gutter);
}

Then I tried to use scss to shorten columns classes description (which at the same time will allow me to change number of columns in one single place in whole code - in CSS Variable --columns) like this

@for $n from 1 through var(--columns) {
  .col-#{$n} {width: calc( #{$n} / var(--columns) - var(--gutter) * 2 ); }
}

but it didn't work. The interesting detail is that when I change @for statement from @for $n from 1 throughvar(--columns)`` to @for $n from 1 through12 it compiles well. And there is no problem in compiling CSS-Variable inside @for body. .col-#{$n} {width: calc( #{$n} / var(--columns) - var(--gutter) * 2 ); } compiles well into needed series of classes.

If I use scss variable $columns instead of CSS variable then I'll need to import my grid.scss file into all other scss files of the project.

It's my first question on StackOverflow, so let me know if any other details are needed.

3 Answers

The accepted answer is no longer valid. Newer versions of SASS require interpolation to be used for variables.

Refer here for more details

$accent-color: #fbbc04;

:root {
  // WRONG, will not work in recent Sass versions.
  --accent-color-wrong: $accent-color;

  // RIGHT, will work in all Sass versions.
  --accent-color-right: #{$accent-color};
}
Related