DEV Community

mikkel250
mikkel250

Posted on

Sass Data Structures

Lists

A list is an ordered collection (aka an array) separated by either spaces or commas, but it's best to pick one stick to it. Mixing spaces and commas will end up creating lists within lists, which may not have been intentional. The syntax looks very similar to a property list, and is intended to mirror CSS, which, for example, will have a mix of space and comma separated values for multiple shadows, which can be read about here.
Lists are NOT zero indexed, they are one indexed.

The @each loop is a handy way to iterate through lists because it is a bit more flexible than a for loop: it will run once for each item in the list, regardless of size. The syntax for lists below creates a new block comment for each item in the list inside the foo class:

// lists
$myList: 0 0 2px #000;
// results in [0, 0, 2px, #000]

// if a comma was added, and more values with spaces:
$myList: 0 0 2px #000, 1 2 3;
// results in [0, 0, 2px, #000, [1, 2, 3]]

.foo {
  @each $i in $myList {
    /* #{$i} */
  }
}
nth

nth is another familiar term from programming, which is a method on a list that has two parameters: the list of values (array), and the item to pluck out (i.e. the nth index). Note that like lists, nth is NOT zero indexed, it is one indexed. Note that in some cases, the parentheses are optional, but for clarity and to avoid unexpected results, it may be best to default to using them:

$gradients:
(to left top, blue, red),
(to left top, blue, yellow);

.foo {
  // sets the linear gradient to the second item 
  background: linear-gradient(nth($gradients, 2));
}

// sets the background to the second item in the gradients list
Maps

Maps are key: value pairs, like objects in JS or hashmaps in many other languages. They resemble CSS property value combinations, which, after all, are key: value pairs themselves.

$myMap: (
  dark: #009; light: #66f;,
);

@mixin theme-button($t) {
  /* Theme: #{$t} */
  color: map-get($myMap, $t);
}

.btn-dark {
  @include theme-button("dark");
}

// CSS
.btn-dark {
  /* Theme: dark */
  color: #009;
}

Top comments (0)