The goal of this tutorial is to guide you on how to create and use lists in SASS/SCSS to store reusable data.
By the end of this tutorial, you will learn:
- How to create lists in SASS/SCSS
- How to access elements in a list
- How to manipulate list data
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and SCSS syntax.
A list in SASS/SCSS is a single variable that stores multiple values. They can be comma or space-separated. To create a list in SASS/SCSS, simply assign multiple space or comma-separated values to a variable.
$font-stack: Arial, sans-serif;
You can access elements in a list using the nth($list, $n)
function, where $list
is the list variable and $n
is the position of the element in the list.
$font-stack: Arial, sans-serif;
$primary-font: nth($font-stack, 1); // Arial
SASS/SCSS provides several built-in functions to manipulate list data, such as length($list)
, append($list, $value)
, join($list1, $list2)
, etc.
$font-stack: Arial, sans-serif;
$font-stack: append($font-stack, 'Helvetica'); // Arial, sans-serif, Helvetica
// Define a list of fonts
$font-stack: Arial, sans-serif, Verdana, 'Courier New';
// Access the first font in the list
.primary-font {
font-family: nth($font-stack, 1); // Arial
}
// Define a list of fonts
$font-stack: Arial, sans-serif;
// Add a new font to the list
$font-stack: append($font-stack, 'Helvetica');
// Check the length of the list
font-length: length($font-stack); // 3
// Join two lists
$more-fonts: Times, 'Courier New';
$all-fonts: join($font-stack, $more-fonts);
.all-fonts {
content: '#{$all-fonts}'; // Arial, sans-serif, Helvetica, Times, 'Courier New'
}
In this tutorial, you learned how to create, access, and manipulate lists in SASS/SCSS. You also learned about the nth
, append
, length
, and join
functions.
To learn more about SASS/SCSS, consider exploring topics such as mixins, functions, and control directives.
Create a list of five colors and use it to set the background colors of five different classes.
$colors: red, blue, green, yellow, purple;
.red {
background-color: nth($colors, 1);
}
.blue {
background-color: nth($colors, 2);
}
.green {
background-color: nth($colors, 3);
}
.yellow {
background-color: nth($colors, 4);
}
.purple {
background-color: nth($colors, 5);
}
Append a new color to the list and use it to set the background color of a new class.
$colors: append($colors, pink);
.pink {
background-color: nth($colors, 6);
}
Join the $colors
list with a new list of your choice and output the resulting list.
$more-colors: black, white;
$all-colors: join($colors, $more-colors);
.all-colors {
content: '#{$all-colors}'; // red, blue, green, yellow, purple, pink, black, white
}