How to Use Functions in Less CSS
HomeHome > News > How to Use Functions in Less CSS

How to Use Functions in Less CSS

Aug 11, 2023

Functions significantly simplify your programming experience, and this holds true when you're writing CSS code as well.

Less CSS is a robust and dynamic CSS preprocessor that has garnered significant attention and popularity in recent years. As a preprocessor, it serves as an extension of "Vanilla CSS," the traditional CSS styling language used in web development, by providing an array of additional features and functionalities that enhance the overall styling experience.

If you are well-versed in writing standard CSS, you can seamlessly transition to using Less CSS without a steep learning curve. This compatibility makes it easy to maintain your existing CSS knowledge while leveraging the advanced capabilities of Less.

In programming, a function is a block of code that performs a specific task. You can also reuse it somewhere else in the program. Functions usually take in data, process it, and return the results.

They make it easy to reduce duplicate code within a program. For example, let's say you have a program that calculates the discount based on the price the user enters. In a language like JavaScript, you could implement it like this:

Then you can call the function and pass in the price and the threshold.

By abstracting away the logic for checking discounts, the program is not only readable, but you now have a reusable block of code that processes the discount and returns the result. There is a lot more that functions can do, but this is just the basics.

In traditional CSS, there is a very limited set of functions available to you as a developer. One of the most popular functions in CSS is the calc() math function which does exactly what it seems—it performs calculations and uses the result as a property value in CSS.

In Less CSS, there are several functions that do more than just arithmetic operations. One function that you may come across in Less is the if function. The if function takes in three parameters: a condition and two values. The code block below shows how you can use this function:

In the code block above, the Less compiler checks if the variable width (defined by the @ symbol) is greater than the variable height. If the condition is true, the function returns the first value after the condition (10px). Otherwise, the function returns the second value (20px).

After the compilation, the CSS output should look something like this:

A boolean is a variable that has two possible values: true or false. With the boolean() function in Less, you can store the true or false value of an expression in a variable for later use. Here's how it works.

In the code block above, the Less compiler checks if text-color is red. Then, the bg-color variable stores the value.

The code block above compiles down to something like this:

The syntax for the replace() function looks like this:

string represents the string that you want to search and replace in. pattern is the string to search for. pattern can also be a regular expression, but it is usually a string. After a successful match, the Less CSS compiler replaces that pattern with the replacement.

Optionally, the replace() function can also contain the flags parameter for regular expression flags.

The code block above should result in the following after compilation:

In Less CSS, you use commas or spaces to define a list of values. For example:

You can use the length() function to evaluate the number of elements in the list.

You can also use the extract() function to extract the value at a particular position. For example, if you want to get the third element in the groceries list, you do the following:

Unlike regular programming languages where the list index starts from 0, the start index of a list in Less CSS is always 1.

Another list function that could come in handy when building websites with Less is the range() function. It takes in three parameters. The first parameter specifies the starting position in the range. The second parameter indicates the end position and the last parameter specifies the increment or decrement value between each item in the range. If not provided, the default value is 1.

The code block above should compile down to the following:

As you can see, the Less CSS compiler starts from 10px, increasing the previous value by 10, until it reaches the end position (40px).

It's time to bring together everything you've learned and create a simple project with Less CSS. Create a folder and add index.htm and style.less files.

Open the index.htm file and add the following HTML code.

In the code block above, there is a parent "container" div with an empty h1 element. The src attribute on the script tag points to the path to the Less CSS Compiler.

Without this script tag, the browser will not be able to understand your code. Alternatively, you can install Less CSS on your computer via Node Package Manager (NPM), by running the following command in the terminal:

Whenever you are ready to compile the .less file, simply run the command below, making sure you specify the file to which the compiler should write the output.

In the style.less file, create two variables namely: container-width and container-bg-color to represent the width and background color of the "container" div respectively.

Next, create three variables namely: string, pattern, and replacement. Then add the styles for the "container" div and the h1 element.

In the code block above, the range() function sets the padding property on the "container" div. The Less compiler should compile the style.less file into the following:

When you open the index.htm file in the browser, this is what you should see:

In regular programming languages, functions reduce the amount of code you need to write and minimize errors. CSS preprocessors like Less, provide several features that make it easier to write CSS code.

CSS preprocessors come in handy when working with large files. They make it easier to debug issues, thereby improving the productivity of the developer.

David Uzondu is a JavaScript Developer with 3+ years of experience. He loves writing in his spare time.

pricethreshold ififwidth@heighttruefalseboolean()text-colorbg-colorreplace()stringpatternpatternpatternreplacementreplace()flagslength()extract()groceriesrange()index.htmstyle.lessindex.htm"container"divh1srcscriptscript.lessstyle.lesscontainer-widthcontainer-bg-color"container"divstringpattern,replacement"container"divh1range()padding"container"divstyle.lessindex.htm