skip to Main Content

I have some lists of SCSS variables which are used in mixins, can I create a ‘master’ list which the others inherit?

$vars: (
  main-colour-active: #0b8579,
  text: #424242,
  button-text: $white,
  font-family: $font-family-base,
);
$nav: (
  inherit $vars,
  background-color: $blue,
);

expected outcome

$nav: (
  main-colour-active: #0b8579,
  text: #424242,
  button-text: $white,
  font-family: $font-family-base,
  background-color: $blue,
);

I have looked into scss inheritance, I know I could add those $vars to a variable within my $nav but would prefer them to all be in one list.

2

Answers


  1. You can use map.merge():

    @use 'sass:map';
    
    $nav-new: map.merge($vars, $nav);
    

    Or:

    $nav: map.merge(
        $vars,
        (
            // ...
        )
    );
    

    Try it:

    @use 'sass:map';
    
    $vars: (
      text: #424242
    );
    
    $nav: (
      text: #fff
    );
    
    $nav-new: map.merge($vars, $nav);
    
    #foo {
        color: map.get($nav-new, text);
    }
    

    …compiles to:

    #foo {
      color: #fff;
    }
    
    Login or Signup to reply.
  2. you can use map-merge also you can get the index number of a map

    $colors1: (
       primary:      red,
       secondary:    blue,
       accent:       #ddd,
    );
    
    $colors2: (
       black:        #000,
       white:        #fff
    );
    
    
    // you can use it like this =>
    
    $colorsGenerated1: map-merge($colors1, $colors2);
    
    @each $key, $value in $colorsGenerated1{
      $i: index($colorsGenerated1, $key $value);
      
      .test1 {
          margin: #{$i}rem;
          background-color: $value;
      }
    }
    
    
    // also you can use it like this =>
    
    $colorsGenerated2: map-merge($colorsGenerated1, (
       pink:        pink,
       purble:        purble
    ));
    
    @each $key, $value in $colorsGenerated1{
      $i: index($colorsGenerated2, $key $value);
          
       .test2 {
           margin: #{$i}rem;
           background-color: $value;
       }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search