Built-in map functions help you work with groups of key-value pairs easily in Sass. They let you find, add, or change values without extra hassle.
0
0
Built-in map functions in SASS
Introduction
When you want to store colors with names and use them later in your styles.
When you need to check if a certain setting exists before applying styles.
When you want to add new options to a list of settings without rewriting everything.
When you want to get all keys or values from a group to use in loops.
When you want to merge two groups of settings into one.
Syntax
SASS
$map: (key1: value1, key2: value2); map.get($map, key1); map.has-key($map, key1); map.merge($map1, $map2); map.keys($map); map.values($map);
map.get gets the value for a key.
map.has-key checks if a key exists.
Examples
This gets the color for 'primary' from the map.
SASS
$colors: (primary: #333, secondary: #666); $primary-color: map.get($colors, primary);
This checks if 'tertiary' color exists before using it.
SASS
@if map.has-key($colors, tertiary) { // do something } @else { // fallback }
This adds a new color to the existing colors map.
SASS
$new-colors: (tertiary: #999); $all-colors: map.merge($colors, $new-colors);
This gets all keys and values separately from the map.
SASS
$keys: map.keys($colors); $values: map.values($colors);
Sample Program
This Sass code creates a map of settings, gets and checks keys, adds a new key, and uses the values in CSS styles. It also shows how to get all keys and values.
SASS
@use 'sass:map'; $settings: ( font-size: 1.2rem, color: #0055cc, margin: 1rem ); // Get font size $font-size: map.get($settings, font-size); // Check if padding exists $has-padding: map.has-key($settings, padding); // Add padding $new-settings: map.merge($settings, (padding: 2rem)); // Get all keys $keys: map.keys($new-settings); // Get all values $values: map.values($new-settings); body { font-size: $font-size; color: map.get($new-settings, color); margin: map.get($new-settings, margin); padding: map.get($new-settings, padding); } /* Keys: #{$keys} */ /* Values: #{$values} */
OutputSuccess
Important Notes
Maps in Sass are like labeled boxes where you keep pairs of names and values.
Use map.get to find a value by its name.
Always check if a key exists with map.has-key before using it to avoid errors.
Summary
Built-in map functions help manage key-value pairs in Sass easily.
You can get, check, add, and list keys and values with simple functions.
Using maps keeps your styles organized and flexible.