0
0
SASSmarkup~5 mins

List values and operations in SASS

Choose your learning style9 modes available
Introduction
Lists in Sass help you group several values together so you can use them easily in your styles.
When you want to store multiple colors to use in different parts of your design.
When you need to keep a set of font sizes to apply consistently.
When you want to loop through a group of values to create repeated styles.
When you want to pass multiple values as one argument to a mixin or function.
Syntax
SASS
$list-name: value1, value2, value3, ...;
Lists are written with values separated by commas or spaces.
You can access list items using the nth() function.
Examples
A list of three colors separated by commas.
SASS
$colors: red, green, blue;
A list of font sizes separated by spaces.
SASS
$sizes: 1rem 1.5rem 2rem;
An empty list with no values.
SASS
$empty-list: ();
A list with only one value.
SASS
$single-item: 10px;
Sample Program
This Sass code creates a list of spacing values. It uses the first and last values for padding and margin in a container. Then it loops through all values to create margin classes with different spacing.
SASS
@use "sass:list";

$spacing-values: 0.5rem, 1rem, 1.5rem, 2rem;

.container {
  // Use the first spacing value
  padding: list.nth($spacing-values, 1);

  // Use the last spacing value
  margin: list.nth($spacing-values, list.length($spacing-values));
}

// Loop through all spacing values to create margin classes
@for $i from 1 through list.length($spacing-values) {
  .margin-#{$i} {
    margin: list.nth($spacing-values, $i);
  }
}
OutputSuccess
Important Notes
Accessing list items with nth() starts counting at 1, not 0.
Lists can be comma-separated or space-separated, but mixing them can cause unexpected results.
Use list.length() to find out how many items are in a list.
Summary
Lists group multiple values together for easy reuse in Sass.
Use commas or spaces to separate list items.
Use nth() to get specific items and length() to get the number of items.