In this tutorial, we'll learn how to modify maps dynamically in SASS/SCSS using the map-merge() function, and explore potential use cases.
By the end of this tutorial, you will be able to:
- Understand the concept of SASS/SCSS maps and how to manipulate them.
- Use the map-merge() function to dynamically modify maps.
This tutorial assumes you have a basic understanding of CSS and a general knowledge of SASS/SCSS.
SASS/SCSS maps are like associative arrays. They store key-value pairs where the keys are used to retrieve values.
map-merge() functionThe map-merge() function merges two maps together into a new map. If both maps have the same key, the second map’s value for that key is used.
$map1: (color: blue, size: 10);
$map2: (color: red, shape: circle);
$new-map: map-merge($map1, $map2);
In this example, $new-map will be (color: red, size: 10, shape: circle). The color value from $map2 overrode the color value from $map1.
map-merge() function when you want to update a few values in a map without affecting the rest.map-merge()$map1: (color: blue, size: 10);
$map2: (color: red, shape: circle);
$new-map: map-merge($map1, $map2);
// Above code will output
// $new-map: (color: red, size: 10, shape: circle)
In this example, we merge $map1 and $map2 into $new-map. The color value in $new-map comes from $map2.
map-merge()$map1: (color: (background: blue, text: white), size: 10);
$map2: (color: (text: black), shape: circle);
$new-map: map-merge($map1, $map2);
// Above code will output
// $new-map: (color: (text: black), size: 10, shape: circle)
Here we have nested maps. The color key in both maps is another map. The map-merge() function replaces the entire value, so the background key from $map1 is lost in $new-map.
In this tutorial, we learned about SASS/SCSS maps and how to dynamically modify them using the map-merge() function. Remember that map-merge() completely replaces any matching keys in the first map with the value from the second map.
For further learning, look into other map functions in SASS/SCSS, such as map-get(), map-remove(), and map-keys().
Given the following maps, merge them into a new map and output the new map.
$map1: (font: Arial, size: 14px);
$map2: (color: black, size: 16px);
Create a map with nested maps and use map-merge() to modify one of the nested maps.
$map1: (font: Arial, size: 14px);
$map2: (color: black, size: 16px);
$new-map: map-merge($map1, $map2);
// This will output: (font: Arial, size: 16px, color: black)
$map1: (styles: (font: Arial, size: 14px), layout: square);
$map2: (styles: (color: black, size: 16px));
$new-map: map-merge($map1, $map2);
// This will output: (styles: (color: black, size: 16px), layout: square)
For further practice, try creating more complex maps and using other map functions in combination with map-merge().