Skip to main content

Use arrays in SASS

Published ago
Updated ago
6 min read

Even though it is a somewhat old tool, for more than 10 years SASS has been one of my best friends in web development, it remains extremely powerful even with the numerous advances in CSS in recent years, because it still has several tools that CSS does not, and they are still useful, such as the ability to use arrays in sass.

Note

SASS?

SASS is a CSS preprocessor, think of it as a compiler in a slightly more technical sense (note, it is not actually a compiler). What it does is give us a new set of tools that are transformed into real CSS when the processor runs, this gives us tools like mix-ins, nesting, inheritance, etc.

One of the most used examples of these tools is the ability to use arrays in sass. This allows us to create loops, maps, etc. This way we can share information between our files and even save several lines of code.

In SASS, arrays are known as lists, in their most basic version, a list is declared as follows:

1$colors: yellow, blue, red, green;
2

This way, we can access any element in the array with the nth function:

1$colors: yellow, blue, red, green;
2@debug nth($colors, 2);
3// style.scss:3 Debug: blue
4

Uses

Now that we have our list declared, we can start using it as it should, the most common use I have found is the printing of utility classes, such as when creating a loop with @each:

1$colors: yellow, blue, red, green;
2@each $color in $colors {
3 .text-#{$color} {
4 color: $color;
5 }
6}
7// Output:
8.text-yellow {
9 color: yellow;
10}
11.text-blue {
12 color: blue;
13}
14.text-red {
15 color: red;
16}
17.text-green {
18 color: green;
19}
20
Tip

Mixing SASS with CSS

If you notice, to print the class name we are wrapping the variable inside some strange symbols #. This is necessary for SASS to recognize that what is inside them should be converted to its true value instead of printing the variable as is.

.text-#{$color} // .text-yellow > .text-$color // .text-$color

On the other hand, when using variables as the value of the property, this is not necessary unless we also mix it with regular text, if not, SASS will do it automatically.

color: $color; // color: yellow

Expanding

Ready! That is a simple way to create and use arrays (or lists) in SASS, as you can see it is very simple, but now what's next? What other uses do you think can be given to it? Do not hesitate to contact me for any questions or leave a comment with other uses that can be given to it. See you!