Sass Map Functions

Sass Tutorial

Sass Map Functions

Sass Map Functions are used to work with maps (key–value pairs).
Maps are extremely powerful for themes, color systems, breakpoints, spacing scales, and configuration-based CSS.


🔹 What Is a Map in Sass?

A map stores values as key: value pairs.

$colors: (
primary: #0d6efd,
success: #198754,
danger: #dc3545
);

🔹 Common Sass Map Functions


1️⃣ map-get()

Gets the value of a key.

map-get($colors, primary);

✔ Output:

#0d6efd

2️⃣ map-has-key()

Checks if a key exists.

map-has-key($colors, success);

✔ Output:

true

3️⃣ map-keys()

Returns all keys as a list.

map-keys($colors);

✔ Output:

primary, success, danger

4️⃣ map-values()

Returns all values as a list.

map-values($colors);

✔ Output:

#0d6efd, #198754, #dc3545

5️⃣ map-merge()

Merges two maps.

$extra-colors: (
warning: #ffc107
);
$new-map: map-merge($colors, $extra-colors);

6️⃣ map-remove()

Removes one or more keys.

map-remove($colors, danger);

7️⃣ map-deep-merge() (Advanced)

Merges nested maps.

$theme1: (
button: (bg: blue, text: white)
);
$theme2: (
button: (bg: green)
);map-deep-merge($theme1, $theme2);


🔹 Looping Through Maps (@each)

@each $name, $color in $colors {
.btn-#{$name} {
background-color: $color;
}
}

✔ Output:

.btn-primary { background-color: #0d6efd; }
.btn-success { background-color: #198754; }
.btn-danger { background-color: #dc3545; }

🔹 Nested Map Example (Breakpoints)

$breakpoints: (
sm: 576px,
md: 768px,
lg: 992px
);
@mixin respond($size) {
@media (min-width: map-get($breakpoints, $size)) {
@content;
}
}

Usage:

.container {
width: 100%;
@include respond(md) {
width: 80%;
}
}

🔹 Real-Life Use Case (Theme System)

$theme: (
light: (
bg: #ffffff,
text: #000000
),
dark: (
bg: #000000,
text: #ffffff
)
);
body.light {
background: map-get(map-get($theme, light), bg);
}

❗ Best Practices

✔ Use maps for configurations
✔ Combine with mixins
✔ Prefer maps over multiple variables
✔ Keep map keys simple


📌 Summary

  • Maps store key–value pairs

  • Very useful for themes & responsive design

  • Powerful built-in functions

  • Works best with loops & mixins

You may also like...