clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Lists in Sass: syntax and use cases with examples

Filed under: Styling— Tagged with: iteration, sass

Sass has lists, which is a similar data structure to an Array or an Object.

Lists in Sass are kind of like arrays, with slight differences. Sass is a modern language, and the fashion has been to conjure up languages that have a very loose syntax, that don’t require you to type things that strictly.

This is one way of saying it’s flexible and free, but on the other hand, loose rules make things more confusing.

Defining a list

Simple list:

$horse-types: pony horse mini-horse maxi-pony;

It can be comma separated if that feels more familiar:

$horse-types: pony, horse, mini-horse, maxi-pony;

If the list items have spaces or other special characters they should be quoted:

$horse-types: 'pony', 'horse', 'mini horse', 'maxi pony';

The lists can be nested:

$hrs: pony #996633, horse #fff, mini-horse #333, maxi-pony #cc9849;

This could be written with parentheses also:

$hrs: (pony #996633) (horse #fff) (mini-horse #333) (maxi-pony #cc9849);

See how to access the values in a nested list later on.

Noteworthy things about lists

  • Indexing starts at 1, not from 0, as in all other programming languages. This is absolutely terrifying.
  • Everything is a list, variables, booleans, strings, anything. This means, that list functions can be used on, say, strings:
$thing: "Fire Walk with me"
length($thing)
// Length is 1

// Drop out quotes, and it’s a list
$thing: Fire Walk with me
length($thing)
// Length is 4

List methods

Here are all the methods we have at our disposal:

NameDescription
length($list)Returns the length of a list.
nth($list, $n)Returns a specific item in a list.
set-nth($list, $n, $value)Replaces the nth item in a list.
join($list1, $list2, [$separator])Joins together two lists into one.
append($list1, $val, [$separator])Appends a single value onto the end of a list.
zip($lists…)Combines several lists into a single multidimensional list.
index($list, $value)Returns the position of a value within a list.
list-separator(#list)Returns the separator of a list.

Accessing a list

Here’s a test list:

$horse-types: pony horse mini-horse maxi-pony;

To access the individual nodes of a list, use the nth() method:

nth($horse-types, 1)
// Results in "pony"

Negative index values address elements in reverse order, starting from end. A good trick if you need to get the last node in a list (don’t have that in JavaScript hah):

nth($horse-types, -1)
// Results in "maxi-pony"

Iterate Sass list with a @for loop:

@for $i from 1 through length($hrs) {
  .horses-#{$i} {
    &:after {
      content: '#{$i}. #{nth($hrs, $i)}';
    }
  }
}

See the demo below for what that piece of code output.

@each loops is the forEach Sass equivalent. This puts some background images to elements:

@each $item in $hrs {
  .hrs-photo-#{$item} {
    background: image-url('img/horses/#{$item}.png') no-repeat;
  }
}

Here’s my Sass loop demo:

Play with this gist on SassMeister.

Accessing nested lists

Remember the nested list from before:

$horses: pony #996633, horse Pink, mini-horse #333, maxi-pony #cc9849;

It contains name/color pairs, in a way it looks a bit like a PHP associative array, or a JavaScript object, if you’re familiar with those.

Here’s a little example:

@each $horse in $horses {
  .horses--#{hth($horse, 1)} {
    background-color: url('#{nth($horse, 2)}');
    background-image: url('img/horse-types/#{nth($horse, 1)}.png') no-repeat;
  }
}

And here’s how that piece of code breaks down:

           ┌──Access the first level
┌──────────┴──────────┐
@each $horse in $horses {
                   ┌──Now that we're in, access the second level
            ┌──────┴───────┐
  .horses--#{hth($horse, 1)} {
                                  ┌──Second level, node 2, the color
                          ┌───────┴───────┐
    background-color: url('#{nth($horse, 2)}');
                                                    ┌──Second level, node 1, the name
                                            ┌───────┴──────┐
    background-image: url('img/horse-types/#{nth($horse, 1)}.png') no-repeat;
  }
}

And a demo for clarity:

Play with this gist on SassMeister.

Adding to a list

Use the aptly named append function.

          ┌──The list where you want to append
          |
          |      ┌──The appended value
       ┌──┴─┐  ┌─┴─┐
append($list1, $val, [$separator])
                      └────┬───┘
                           └─Just 'comma' or 'space'

The appending is usually done inside a loop:

// The list
$horse-types: pony horse mini-horse maxi-pony;

// The thing to append
$another-type-of-pony: shetland;

// The append itself
$horse-types: append($horse-types, unquote($another-type-of-pony), space);
// Outputs: pony horse mini-horse maxi-pony shetland

Notes about adding to lists:

  • The added value might need to be unquotes with the unquote function.
  • The separator is just an english name for the character, like 'comma' or 'space'.
  • If using comma as the separator value in the original list, and space in the append, then the whole list is converted to space separated list.

Common use cases for lists

For instance, pass a list to a mixin, here’s a little rounded corners example:

@mixin round-corner($corners: 0 0 0 0) {
  $top-left: nth($corners, 1);
  $top-right: nth($corners, 2);
  $bottom-right: nth($corners, 3);
  $bottom-left: nth($corners, 4);

  border-top-left-radius: $top-left;
  border-top-right-radius: $top-right;
  border-bottom-right-radius: $bottom-right;
  border-bottom-left-radius: $bottom-left;
}

Lists excel at passing parameter to mixins for example.

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!