0
0
SASSmarkup~5 mins

Accessing map values with map-get in SASS

Choose your learning style9 modes available
Introduction

Maps in Sass let you store pairs of related information. Using map-get helps you find the value for a specific key easily.

You want to store colors with names and use them later in styles.
You have a list of font sizes labeled by purpose and want to apply them.
You keep spacing values grouped by size names and need to reuse them.
You want to organize theme settings and access them by keys.
Syntax
SASS
map-get($map, $key)

$map is the map variable you want to look inside.

$key is the name of the item you want to find.

Examples
This gets the value for primary from the $colors map and uses it as text color.
SASS
$colors: (primary: #0055ff, secondary: #ff5500);

.primary-color {
  color: map-get($colors, primary);
}
This sets the font size of a button using the medium size from the $sizes map.
SASS
$sizes: (small: 0.8rem, medium: 1rem, large: 1.5rem);

.button {
  font-size: map-get($sizes, medium);
}
This applies padding and margin by getting values from the $spacing map.
SASS
$spacing: (padding: 1rem, margin: 2rem);

.container {
  padding: map-get($spacing, padding);
  margin: map-get($spacing, margin);
}
Sample Program

This Sass code defines a map of theme colors. It then uses map-get to apply the background and text colors to the body. The .highlight class uses the highlight color from the map.

SASS
@use "sass:map";

$theme-colors: (
  background: #f0f0f0,
  text: #333333,
  highlight: #ffcc00
);

body {
  background-color: map-get($theme-colors, background);
  color: map-get($theme-colors, text);
}

.highlight {
  background-color: map-get($theme-colors, highlight);
  padding: 1rem;
  border-radius: 0.5rem;
}
OutputSuccess
Important Notes

If the key does not exist in the map, map-get returns null.

Maps help keep your styles organized and easy to update.

Summary

map-get finds a value by its key inside a Sass map.

Use it to keep your style values neat and reusable.

Always check your keys to avoid getting null.