Skip to content

Instantly share code, notes, and snippets.

@sivan
Last active May 14, 2020 19:34
Show Gist options
  • Save sivan/3f1aca9511fd0d11a23d6badaffe9f1e to your computer and use it in GitHub Desktop.
Save sivan/3f1aca9511fd0d11a23d6badaffe9f1e to your computer and use it in GitHub Desktop.
Use CSS variable safety.
// Use CSS variable safety
@mixin use-var($property, $value, $fallback: false, $compatible-mode: false) {
// if fallback value given
@if $fallback {
// if need compatible selector
@if $compatible-mode {
@if type-of($compatible-mode) == string {
#{$property}: var(--#{$value}, #{$fallback});
#{$compatible-mode} & {
#{$property}: $fallback;
}
} @else {
#{$property}: $fallback;
#{$property}: var(--#{$value}, #{$fallback});
}
} @else {
#{$property}: var(--#{$value}, #{$fallback});
}
} @else {
#{$property}: var(--#{$value});
}
}
:root {
--color-brand: #ff6700;
}
/* For modern browser only */
.header {
@include use-var(background-color, color-brand);
}
/* For modern browser with fallback value */
.header {
@include use-var(background-color, color-brand, #000);
}
/* For legacy browser with test */
.header {
@include use-var(background-color, color-brand, #000, '.no-custom-properties');
}
/* For legacy browser */
.header {
@include use-var(background-color, color-brand, #000, true);
}
:root {
--color-brand: #ff6700;
}
/* For modern browser only */
.header {
background-color: var(--color-brand);
}
/* For modern browser with fallback value */
.header {
background-color: var(--color-brand, #000);
}
/* For legacy browser with test */
.header {
background-color: var(--color-brand, #000);
}
.no-custom-properties .header {
background-color: #000;
}
/* For legacy browser */
.header {
background-color: #000;
background-color: var(--color-brand, #000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment