'Using escaped selectors in Sass maps
In our CSS we have escaped characters in our selectors using \ like so:
.width-1\.5 { width: 1.5rem; }
.width-1\/2 { width: 50%; }
So this allows us to have CSS classes like: class="width-1/2"
And we store all of these values in Sass maps like:
$widths: (1\.5: 1.5rem, 1\/2: 50%);
And then we create the CSS with a simple loop:
@each $key,
$value in $widths {
.width-#{$key}: $value
}
However we get the error: SassError: 1\/2 isn't a valid CSS value.
So it's fine with \. but it doesn't like: \/. Even though outside of Sass it's fine to use this syntax to escape the /.
If we wrap the keys in quotes in the map like this:
$widths: ('1\.5': 1.5rem, '1\/2': 50%);
Sass removes the escape character so it becomes just 1/2 and therefore an invalid CSS selector with: SassError: Invalid CSS after ".width-1": expected selector, was "/2".
How can we create this syntax using Sass maps?
Solution 1:[1]
The solution was to use the quote function:
$widths: (quote(1\/2): 50%);
Solution 2:[2]
I was able to make this work by double-escaping the punctuation. E.g.:
$widths: (
'1\\.5': 1.5rem
)
For what it's worth, I'm using the sass NPM package. Not sure if there's a discrepancy between Dart Sass, node-sass, or other implementations that would affect whether this works or not.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cameron |
| Solution 2 | wosephjeber |
