DEV Community

Discussion on: Write CSS variables faster in SCSS

Collapse
 
vinceumo profile image
Vincent Humeau • Edited

Hey, cool way.

I use a different approach, I set all my scss variables in maps, so I can link them to a function and return the css variables. I have a flag as well in case I want to use the real value.


// In _settings.scss $use-css-var: true;


// ------------------------------
// Sass Variables
// ------------------------------
$variable-prefix: --variable-; // CSS Variable prefix

$variables: (
  val1: 1,
  val2: 2,
  val3: 3 // etc.
);

// ------------------------------
// Set variable function
// ------------------------------
@function myVariable($variable, $true-val:false) {
  @if $use-css-var == true {
    @if $true-val == true {
      @return map-get($variables, $variable); //True Val
    } @else {
      @return var(#{$variable-prefix}#{$variable}); //CSS Var
    }
  } @else {
    @return map-get($variables, $variable); //Disabled CSS Var
  }
}

  // If $use-css-var == true
    // myVariable(val1) => var(--variable-val1)
    // myVariable(val2, true) => 2
  // If $use-css-var == false
    // myVariable(val3) => 3
    // myVariable(val2, true) => 2

// ------------------------------
// Set root variables
// ------------------------------
@if $use-css-var == true {
  :root{
    @each $name, $variable in $variables {
      #{$variable-prefix}#{$name}: $variable;
    }
  }
}

  // Output if $use-css-var == true
  // :root{
  //   --variable-val1: 1;
  //   --variable-val2: 2;
  //   --variable-val3: 3;
  //   /*etc.*/
  // }

vinceumo.github.io/devNotes/sass/2...

Collapse
 
equinusocio profile image
Mattia Astorino • Edited

Can your function be rewritten like this?

@function myVariable($variable, $true-val:false) {
  @if $use-css-var == true and $true-val == true  {
    @return map-get($variables, $variable); //True Val
  } @else {
    @return var(#{$variable-prefix}#{$variable}); //CSS Var
  }
}
Collapse
 
meduzen profile image
Mehdi M. • Edited

I just noticed the title of my article may lead to confusion: it’s more about accessing to the variable once defined, it’s not about the variable definition, which is a topic covered by your article.

What you write reminds me the css-vars package or the postcss-custom-properties plugin, which both seems very similar to what you do.

I’m currently working on a SCSS workflow for Custom Media Queries, this time more on the media query definition. It will leverage the postcss-custom-media and postcss-media-minmax plugins, and from what I’m testing, it’ll be the faster way to both declare and use media queries I’ve ever encounter. (Huge statement. :D)