Skip to content

Instantly share code, notes, and snippets.

@macgyver
Last active July 26, 2018 23:43
Show Gist options
  • Save macgyver/878c433a1fde39db28a4377945019df9 to your computer and use it in GitHub Desktop.
Save macgyver/878c433a1fde39db28a4377945019df9 to your computer and use it in GitHub Desktop.
Sass utility functions for working with css variables
// n.b. assumes a code formatter (eg. Prettier) which enforces that css vars look exactly like `var(--x[, y])`
// var(--x) -> true
// var(--x, red) -> true
// red -> false
@function is-css-var($str-val) {
@return str-index($str-val, "var(--") == 1;
}
// var(--x, y) -> y
// var(--x) -> null
@function get-css-var-fallback($str-val) {
$fallback-start: str-index($str-val, ", ");
$fallback-end: str-index($str-val, ")");
@if $fallback-start and $fallback-end {
$fallback: str-slice($str-val, $fallback-start + 1, $fallback-end - 1);
@return $fallback;
}
@return null;
}
/*
adds constant fallback value for browsers that don't support css vars
$prop: a css property, eg. `color`
$val: a value, which may contain css variables w/ fallback values, .g. `var(--x, red)`
(border-color, red) ->
border-color: red;
(border-color, var(--x)) ->
border-color: var(--x);
(border-color, var(--x, red)) ->
border-color: red;
border-color: var(--x, red);
*/
@mixin with-fallback($prop, $val) {
$str-val: inspect($val);
@if is-css-var($str-val) {
#{$prop}: get-css-var-fallback($str-val);
}
#{$prop}: $val;
}
/*
making this gist for posterity, but I ended up not using this and recommend you don't either,
because it's more stupid obvious to just double up on properties that reference css variables, eg.
```scss
color: red;
color: var(--x, red);
```
or
```scss
@include crazy-mixin(red); // IE11 fallback
@include crazy-mixin(var(--x, red));
```
...and trust in postcss to trim the duplicate properties.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment