Lists

Group multiple values with spaces or commas.

Syntax$sides: 10px 20px 30px; $fonts: Arial, sans-serif;

A list is an ordered series of values, separated by spaces or commas. Many CSS values are already lists — margin: 10px 20px is a two-item space-separated list.

Working with lists

Use the sass:list module to read and build lists: list.nth() gets an item (1-based), list.length() counts items, and list.append() adds one.

Example

Example · css
@use 'sass:list';

$breakpoints: 480px, 768px, 1024px;

@debug list.length($breakpoints); // 3
@debug list.nth($breakpoints, 2); // 768px

@each $bp in $breakpoints {
  // ...generate a media query per breakpoint
}

When to use it

  • A developer stores the names of all breakpoints in a Sass list and loops over it to generate responsive modifier classes for every component.
  • A mixin receives a list of box-shadow values and applies them all at once, letting callers stack multiple shadows as a single argument.
  • A design system stores the ordered steps of a type scale in a list, then uses nth() to pull individual values into heading and body styles.

More examples

Iterating over a list

Loops over a four-item list to generate border utility classes for every side without repeating selector patterns.

Example · css
$sides: top, right, bottom, left;

@each $side in $sides {
  .border-#{$side} {
    border-#{$side}: 1px solid #ccc;
  }
}

Accessing list items with nth()

Stores a type scale as a list and retrieves specific steps by index using sass:list's nth() function.

Example · css
@use 'sass:list';

$scale: 0.75rem, 1rem, 1.25rem, 1.5rem, 2rem;

h1 { font-size: list.nth($scale, 5); } // 2rem
h2 { font-size: list.nth($scale, 4); } // 1.5rem
p  { font-size: list.nth($scale, 2); } // 1rem

Building a list dynamically

Builds a multi-layer box-shadow by appending values to an initially empty list, then assigns the complete list to a property.

Example · css
@use 'sass:list';

$shadows: ();
$shadows: list.append($shadows, 0 1px 3px rgba(0,0,0,.12));
$shadows: list.append($shadows, 0 4px 6px rgba(0,0,0,.08));

.card {
  box-shadow: $shadows;
}

Discussion

  • Be the first to comment on this lesson.