How to assign css variable value to scss variable or expression

I am trying to create my own tiny scalable grid in CSS / scss. So far I have found this solution:

: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 the column class description (which at the same time allows me to change the number of columns in one place in the whole code - in the 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. An interesting detail is that when the instruction is changed @for

from, to, it compiles well. And there is no problem compiling a CSS-Variable inside the body . compiles well into the desired set of classes.@for $n from 1 through

var(--columns)

@for $n from 1 through

12

@for

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

If I use a scss variable $columns

instead of a CSS variable then I will need to import the grid.scss file into all the other scss files in the project.

This is my first question on StackOverflow, so let me know if any other data is needed.

+3


source to share


2 answers


CSS Variables and SCSS are two different things (see this pen )

To do this 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
: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 ); }

}

      

+3


source


You need to use interpolation (like # {$ var}) on the variable for Sass to treat it as a CSS property. Without it, you are just doing variable assignments.



@mixin w_fluid($property_name, $w_element, $w_parent:16) { #{$property_name}: percentage(($w_element / $w_parent)); }

+1


source







All Articles