Feature Request: Automated conversion between Sass variables and CSS custom properties
See original GitHub issueProposal
I find the syntax for using a CSS custom property to be tedious, and much prefer the Sass syntax. So, I propose that there be a new way to assign CSS custom properties using Sass/SCSS syntax.
This would enable designated variables to be changed at runtime (among other advantages), while maintaining the benefits of Sass variables.
I’m not sure what the precedent for something like this would suggest, but this option could perhaps be enabled in a CLI flag, an environment variable, or as a variation of the current variable declaration syntax.
Examples
Basic Example
$foo: 10px; // or any alternate syntax
.bar {
width: $foo;
height: $foo;
}
:root {
--foo: 10px;
}
.bar {
width: var(--foo);
height: var(--foo);
}
Example with media query
$foo: 10px; // or any alternate syntax
@media screen and (min-width: 768px) {
$foo: 20px;
}
.bar {
width: $foo;
height: $foo;
}
:root {
--foo: 10px;
}
@media screen and (min-width: 768px) {
:root {
--foo: 20px;
}
}
.bar {
width: var(--foo);
height: var(--foo);
}
Namespacing
I understand that there could be the possibility of collisions since Sass variables are contained to the working file whereas CSS custom properties defined in the root selector are not. So, it might be necessary to map the given Sass variable names to a more obscure property name.
For example, mapping $foo
to --[directory/file]-foo-[hash]
.
Thanks.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (2 by maintainers)
Top GitHub Comments
Sass variables & CSS custom properties are fundamentally different – I don’t think it will ever be safe for us to implicitly generate one from the other.
And if the goal is only to save a few keystrokes, I’m not sure Sass is the right place for that to happen – at the expense of very useful CSS custom property features like the fallback value of the
var()
function. I’d recommend using text snippets in your code editor.The best I could imagine here is something more explicit (like a mixin) for generating CSS props from Sass variables, without needing to duplicate the name, or call a variable with a Sass-defined fallback:
compiling too:
I might find something like that useful as a shortcut - especially if the “create” mixin could accept any number of variables.
Sass variables and CSS custom properties are different enough that having any sort of automatic link between them isn’t something we’d want to add to the language. Users should explicitly link the specific variables/custom properties that they want to connect.
The problem with something like
var.use
andvar.create
is that they require introspection into what variable is actually passed to them (rather than normal functions that only care about the value that variable evaluates to). This would be complex to implement and would violate referential transparency, so it’s not something we’re likely to add.