Skip to content

Less - List Functions

LESS provides functions to work with lists. In LESS, a list is a sequence of values separated by either commas or spaces. These functions allow you to inspect and extract values from lists, making your stylesheets more dynamic and programmable.

Key list functions include:

Sr.No.FunctionDescription
1length(list)Returns the number of elements in a list. The list can be comma-separated or space-separated.
2extract(list, index)Returns the value at a specific index within the list. Importantly, list indexing in LESS is 1-based, meaning the first element is at index 1, the second at index 2, and so on.

This function counts the items in a list.

LESS Code:

@framework-paddings: 10px 20px 15px 25px;
@color-palette: red, green, blue;
.element-padding-count {
content: length(@framework-paddings); // space-separated list
}
.color-count {
content: length(@color-palette); // comma-separated list
}

Compiled CSS:

.element-padding-count {
content: 4;
}
.color-count {
content: 3;
}

This function retrieves an item from a list by its index (1-based).

LESS Code:

@font-sizes: 12px, 16px, 24px, 32px;
@spacings: 5px 10px 15px 20px;
.title {
font-size: extract(@font-sizes, 3); // Gets the 3rd item: 24px
}
.card {
margin-top: extract(@spacings, 2); // Gets the 2nd item: 10px
padding-left: extract(@spacings, 4); // Gets the 4th item: 20px
}

Compiled CSS:

.title {
font-size: 24px;
}
.card {
margin-top: 10px;
padding-left: 20px;
}

List functions are particularly useful when creating utility classes or managing a set of related values like a color palette or spacing scale. For instance, you could iterate over a list using loops (with mixins and recursion, or the each() function in newer LESS versions) to generate a series of helper classes.

For more advanced list manipulation, you might also explore the each() function. (For details, refer to the official LESS documentation: lesscss.org/functions/#list-functions)