Sass Reference - - By Hugo Giraudel

Maps

Sass has been supporting lists for a long time now but it is actually quite new that we can use actual associative arrays (or hashes) within our Sass powered stylesheets.

To put it simply, a map is a collection of associated keys and values, where both can be of any type, even lists or maps. Those values can either be accessed with native Sass functions such as map-get, or iterated with the @each extended notation.

Examples

Let’s start with a very simple example:

// Defining a map
$colors: (
  'brand': hotpink,
  'grey': silver,
  'black': #333,
);

// Accessing specific value
body {
  color: map-get($colors, 'black');
}

// Iterating over a map
@each $color-name, $color in $colors {
  .living-styleguide::before {
    content: quote($color-name);
    color: $color;
  }
}

Sass maps can be extremely powerful to store data as part of larger systems. For instance, it can be interesting to use a map to store icon-related data:

$icons: (
  glass: "\f000",
  music: "\f001",
  search: "\f002",
  envelope: "\f003",
  heart: "\f004"
);

@each $name, $icon in $icons {
  .icon-#{$name}:before {
    content: quote($icon);
  }
}

For further examples of maps usage, refer to this article.

Iterating on maps

There are several ways to iterate over a map, and all of them include the use of a loop. Please refer to the loops entry in order to learn more about loops.

Map manipulation functions

Sass provides a collection of native functions to manipulate maps:

// Initializing an empty map
$map: (); // ()

// Getting the number of items in map
$count: length($map); // 0

// Adding a value to the map
$map: map-merge($map, ('foo': 1)); // ('foo': 1)

// Getting the number of items in map
$count: length($map); // 1

// Adding several items at once in map
$map: map-merge($map, ('bar': 2, 'baz': 3)); // ('foo': 1, 'bar': 2, 'baz': 3)

// Getting the number of items in map
$count: length($map); // 3

// Remove item from map
$map: map-remove($map, 'bar'); // ('foo': 1, 'baz' 3)

// Checking whether map has specific key
$has: map-has-key($map, 'bar'); // false

// Updating value in the map
$map: map-merge($map, ('foo': 10)); // ('foo': 10, 'baz': 3)

// Getting the value mapped to `foo`
$item: map-get($map, 'foo'); // 10

// Getting all keys from map
$keys: map-keys($map); // 'foo', 'baz'

// Getting all values from map
$values: map-values($map); // 10, 3

// Getting the first value from map
$item: nth(map-values($map), 1);

For further map functions, refer to this article.

Engine compatibility

Maps are supported starting Ruby Sass 3.3. Otherwise, there is no known bug to this day about their implementation.