How to add $ sign in front of sass variables in @each loop

Viewed 40
$root-sizes:(
    'desktop': 20px,
    'mobile': 16px
);

@each $viewport,$size in $root-sizes{
    @media screen and (max-width: '$brk-'#{$viewport}){
        html{
            font-size: $size;
        }
    }
}

I was expecting the output to be

$brk-desktop

but it outputs $brk- desktop //with a space

1 Answers

It is not possible to access SCSS-variables dynamically like that. Check this similar question out.

A quite simple workaround for this problem is to create an extra map and access those values through your each-loop. Here's a working example:

$brk-sizes: (
  "desktop": 1200px,
  "mobile": 600px,
);

$root-sizes: (
  "desktop": 20px,
  "mobile": 16px,
);

@each $viewport, $size in $root-sizes {
  @media screen and (max-width: map-get($brk-sizes, $viewport)) {
    html {
      font-size: $size;
    }
  }
}

Since you have 2 maps you could also create an extra function for that in order to make your code more readable and reasonable:

$brk-sizes: (
  "desktop": 1200px,
  "mobile": 600px,
);

$root-sizes: (
  "desktop": 20px,
  "mobile": 16px,
);

@function get-matching-viewport-size($viewport) {
  @return map-get($brk-sizes, $viewport);
}

@each $viewport, $size in $root-sizes {
  @media screen and (max-width: get-matching-viewport-size($viewport)) {
    html {
      font-size: $size;
    }
  }
}
Related