Search code examples
csssasscss-variables

How to Assign CSS Variable Value to scss Variable or Expression


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.


Solution

  • CSS and SCSS variables are two very different things (please see this pen)

    To make it work you need a static variable for SCSS to compile

    // static (SCSS) variables used produce CSS output
    $page-width: 1170px;
    $gutter : 15px
    $columns: 12;  
    
    // dynamic (CSS) variables used at run-time
    // note the values are interpolated 
    :root {
      --page-width: #{$page-width};
      --gutter : #{$gutter};
      --columns: #{$columns};
    }
    
    //  the for loop is aimed at producing CSS output
    //  ... why you need the static variable
    @for $n from 1 through $columns {  
      
      //  the content becomes CSS output
      //  ... why you can use dynamic variables   
      .col-#{$n} {width: calc( #{$n} / var(--columns) - var(--gutter) * 2 ); }
    
    }