DEV Community

mrtoxas
mrtoxas

Posted on

Easy SCSS color-function

I decided to share with you a function that makes my life easier. Function organizes convenient work with colors on the page, uses css-variables.

// Creating a map with our colors:
$colors: (
  primary:#f37021,
  secondary:#b4341d,  
);

// Declaring colors as global variables of page
:root {
  @each $name, $color in $colors {
    --color-#{$name}: #{$color};
  }
}

/* Creating a function that returns our color, 
in accordance with the syntax of css-variables */
@function color($color-name) {
  @return var(--color-#{$color-name});
}

// Usage
body{
  color: color(primary);
  background-color: color(secondary);
}
Enter fullscreen mode Exit fullscreen mode

At the output we get the result:

:root {
  --color-primary: #f37021;
  --color-primary-dark: #CE5A14;
}

body {
  color: var(--color-primary);
  background-color: var(--color-secondary);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)