We use cookies to enhance your experience on the site
CodeWorlds

Maps and Lists in Sass

Sass offers two data structures that allow better organization of values: maps and lists. Think of them like treasure catalogs in an Egyptian temple - lists are ordered inventories, and maps are catalogs with descriptions.

Lists in Sass

A list is a collection of values separated by spaces or commas. It's like a papyrus scroll listing the names of pharaohs.

1// Space-separated list
2$font-stack: Helvetica, Arial, sans-serif;
3
4// Comma-separated list
5$sizes: 12px, 14px, 16px, 18px, 24px;
6
7// Iterating over a list with @each
8@each $size in $sizes {
9  .text-#{$size} {
10    font-size: $size;
11  }
12}

Useful functions for working with lists:

  • length($list)
    - returns the number of elements
  • nth($list, $index)
    - returns the element at the given index (index starts from 1)
  • append($list, $value)
    - adds an element to the end
  • join($list1, $list2)
    - merges two lists
1$colors: red, blue, green;
2
3.element {
4  color: nth($colors, 2); // blue
5}

Maps in Sass

A map is a collection of key-value pairs, like a cryptographic catalog of Egyptian artifacts. We define it using parentheses.

1$breakpoints: (
2  "mobile": 320px,
3  "tablet": 768px,
4  "desktop": 1024px,
5  "wide": 1440px
6);
7
8$colors: (
9  "primary": #2C3E50,
10  "secondary": #D4AF37,
11  "accent": #E74C3C,
12  "background": #F5F0E1
13);

To retrieve a value from a map, we use the

map-get()
function:

1.header {
2  background-color: map-get($colors, "primary");
3  color: map-get($colors, "secondary");
4}

Iterating Over Maps with @each

We can automatically generate classes based on a map:

1@each $name, $color in $colors {
2  .text-#{$name} {
3    color: $color;
4  }
5  .bg-#{$name} {
6    background-color: $color;
7  }
8}

After compilation, we'll get classes like

.text-primary
,
.text-secondary
,
.bg-primary
, etc.

Maps for Breakpoints

One of the most common uses of maps is storing breakpoints and using them in media queries:

1$breakpoints: (
2  "sm": 576px,
3  "md": 768px,
4  "lg": 1024px,
5  "xl": 1200px
6);
7
8@mixin respond-to($breakpoint) {
9  $value: map-get($breakpoints, $breakpoint);
10  @media (min-width: $value) {
11    @content;
12  }
13}
14
15.container {
16  width: 100%;
17
18  @include respond-to("md") {
19    width: 750px;
20  }
21
22  @include respond-to("lg") {
23    width: 970px;
24  }
25}

Useful Map Functions

  • map-get($map, $key)
    - retrieves a value
  • map-has-key($map, $key)
    - checks if a key exists
  • map-keys($map)
    - returns a list of keys
  • map-values($map)
    - returns a list of values
  • map-merge($map1, $map2)
    - merges two maps

Maps and lists are higher-level code organization tools - they allow you to store configuration in one place and generate styles automatically, like an efficient resource management system in an ancient temple.

Go to CodeWorlds