DEV Community

Nicola
Nicola

Posted on

Using SCSS maps as object - is it good?

Hi to all!

For my latest project I've preferred to use SCSS maps instead of simple SCSS variables.

For example:

$fontSizes: (
  extraSmall: .75rem,
  small: .9rem,
  normal: 1rem,
  medium: 1.25rem,
  big: 1.5rem,
  extraBig: 2rem
);

So I can get those values around my stylesheets as follow:

font-size: map_get($fontSizes, extraSmall);

I just LOVE this method, I've converted all my SCSS variables (excluding the atomic variables like $globalBorderRadius) into maps, so I can group them into a specific set of scss variables.

What do you think about SCSS maps?
Have you ever used them? If yes, is this a good way to use them?

Let me know! :)

Top comments (5)

Collapse
 
vicvicvic profile image
Victor F

And now the next step: convert these into functions:

@function fontsize($key) {
@if not map-has-key($fontSizes, $key) {
@warn "Color `#{$key}` not found.";
}
@return map-get($fontSizes, $key);
}

Collapse
 
nicolalc profile image
Nicola

That's pretty cool, I think I'll implement in my projects! Thanks a lot!

Collapse
 
teetotum profile image
Martin

I understand that it is highly subjective for every developer what feels elegant. If there is any good reason to group variables together the scss map is the right thing to use. But for the example you have posted I would still prefer the simpler font-size: $font-size-extra-small; over font-size: map_get($fontSizes, extraSmall); or font-size: fontsize('extraSmall');

Collapse
 
aniketbhalla2544 profile image
Aniket Bhalla

I'm generating classes through scss-maps.
Would there be any performance issues on browser for loading all these classes??

// font-weights
$font-weights: (
"100": 100,
"200": 200,
"300": 300,
"400": 400,
"500": 500,
"600": 600,
"700": 700,
"800": 800,
"900": 900,
);

@each $fw-name, $fw-value in $font-weights {
.fw-#{$fw-name} {
font-weight: $fw-value;
}
}

Collapse
 
neilh profile image
Neil Haskins • Edited

Old post, I know.

This font-weight example could be done with a list instead of a map, which would be my preference.

// font-weights
$font-weights: [100, 200, 300, 400, 500, 600, 700, 800, 900];

@each $fw in $font-weights {
    .fw-#{$fw} {
        font-weight: $fw;
    }
}
Enter fullscreen mode Exit fullscreen mode

The performance impact should be so negligible it would be hard to even measure.