How to use Sass maps

How to use Sass maps

Sass maps arrived in the Sass 3.3 release, a data structure to store key/value pairs. There are many uses for maps, here's an example with social media icons.

Map syntax

Maps are a Sass data type used to store key/value pairs. The key is used to look up the associated value. This is the syntax for a map.

 $map: (key1: value1, key2: value2, key3: value3);

Map functions

Sass docs have a full list of map functions.

In our example we're only going to use map-get which returns the value of the specified key. It is used like so:

$map: (key1: value1, key2: value2, key3: value3);
$result : map-get($map, "key2"); // returns "value2"

Social image map

Lets create a map to hold our social media images and a function to retrieve them. Here's our map.

$social: (
  facebook: "facebook.png",
  googleplus: "google-plus.png",
  twitter: "twitter.png"
);

Then a simple function to retrieve the required social image value.

// Returns the image for the specified social media name
@function socialIcon($type){
  @return map-get($social, $type);
}

// usage
.facebook { background-image: socialIcon(facebook);}

// outputs
.facebook {
  background-image: "facebook.png";
}

Social media icon font map

Or with a icon font like font awesome.

$social: (
  facebook: "\f230",
  googleplus: "\f0d5",
  twitter: "\f099"
);

.ico-facebook:after { content: socialIcon(facebook);}

// outputs
.ico-facebook:after {
  content: "\f230";
}

Using a deeper structure

Maps can contain maps. Nesting allows for larger data structures, grouping data by type. Using our social media example.

 $social: (
  facebook: (
    icon: "\f230",
    colour: '#000'
  ),
  googleplus: (
    icon: "\f0d5",
    colour: '#fff'
  ),
  twitter: (
    icon: "\f099",
    colour: '#eee'
  )
);

Now we have data grouped by social media type. To retrieve values from a nested map we need to call map-get twice. The first get will return the nested map which we can get the value from the specified key. Again we can create a function to make it easier for us.

// Returns a value from the specified set with the specified key
@function socialSet($set, $key){
  @return map-get(map-get($social, $set), $key);
}

Then we can use it like this.

// usage
.smokey {
  background-color: socialSet(twitter, colour);
  &:after {
    content: socialSet(twitter, icon);
  }
}

// outputs
.smokey {
  background-color: "#eee";
}

.smokey:after {
  content: "\f099";
}

Summary

In this example we have learnt about maps and how we can use them to group and collate values of a particular type. We then manipulated our map by creating functions to retrieve the value for a specified key. This is just one example of how we can use maps, the possibilities are endless, give it a try!