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.
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 elementsnth($list, $index) - returns the element at the given index (index starts from 1)append($list, $value) - adds an element to the endjoin($list1, $list2) - merges two lists1$colors: red, blue, green;
2
3.element {
4 color: nth($colors, 2); // blue
5}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}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.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}map-get($map, $key) - retrieves a valuemap-has-key($map, $key) - checks if a key existsmap-keys($map) - returns a list of keysmap-values($map) - returns a list of valuesmap-merge($map1, $map2) - merges two mapsMaps 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.