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.
source to share
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 ); }
}
source to share