How to use functions in Less CSS
Functions greatly simplify the programming experience, especially when writing CSS code. Here's how to use functions in Less CSS.
Less CSS is a dynamic and powerful CSS preprocessor that has been popular in recent years. As a preprocessor, it acts as an extension of "Vanilla CSS" by providing a host of additional features and functions that enhance the overall styling experience.
If you've mastered writing standard CSS, you can seamlessly transition to using Less CSS without much learning. This makes it easy to maintain your existing CSS knowledge while taking advantage of Less's advanced features.
What are functions and why are they important?
In programming, a function is a block of code that executes a specific task. You can also reuse it somewhere else in the program. Functions typically take data, process it, and return results.
They make it easy to reduce code duplication in a program. Suppose you have a program that calculates a discount based on a price entered by a user. In a language like JavaScript, you can implement it like this:
function checkDiscount(price, threshold){ if (price >= threshold){ let discount = 5/100 * price; return `Your discount is $${discount}`; } else { return `Sorry, this item does not qualify for a discount. ` } }
You can then call this function and pass it to price and threshold.
let price = prompt("Enter the item price: ") alert(checkDiscount(price, 500))
By removing the logic for checking the discount, the program is not only readable, but you now have a reusable block of code to handle the discount and return the result. Functions can do many more things, the above are just the basics.
What is a function in Less CSS?
Traditional CSS has a very limited number of functions for the programmer. One of CSS's most popular functions is the math function calc() which does exactly what it does—it performs calculations and uses the results as property values in CSS.
p{ background-color: red; width: calc(13px - 4px); }
Less CSS has several functions that do more than just arithmetic. One function that you may come across in Less is the if function. The if function takes three parameters: a condition and two values. The code block below shows how you can use this function:
@width: 10px; @height: 20px; div{ margin:if((@width > @height), 10px, 20px) }
In the above code block, the Less compiler checks if the width of the variable (determined by the @ symbol) is greater than the height of the variable. If the condition is true, the function returns the first value after the condition (10px). Otherwise, the function returns the second value (20px).
After compiling, the CSS output should look like this:
div { margin: 20px; }
How to use Boolean in CSS
A Boolean is a variable that can have two 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 is how it works.
@text-color: red;
In the above code block, the Less compiler checks to see if the text-color is red. Then the bg-color variable contains this value.
div{ background-color: if(@bg-color,green,yellow); }
The code block above compiles to the following output:
div { background-color: green; }
Replace text in a string with the replace() function
The replace() function syntax looks like this:
replace(string, pattern, replacement, flags)
string represents the string that you want to search and replace. 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 Les CSS compiler will replace the pattern with replacement.
Optionally, the replacemen() function can also contain a flags parameter for the regular expression flag.
@string: "Hello"; @pattern: "ello"; @replacement: "i"; div::before{ content: replace(@string,@pattern,@replacement) }
Result:
div::before { content: "Hi"; }
List function in Less CSS
In Less CSS, you use commas or spaces to define a list of values. For example:
@groceries: "bread", "banana", "potato", "milk";
You can use the length() function to evaluate the number of elements in the list.
@result: length(@groceries);
You can also use the extract() function to extract the value at a specific location. For example, if you want to get the 3rd element in the grocery list, do the following:
@third-element: extract(@groceries, 3);
Unlike conventional programming languages where list indexes start at 0, the list's starting index in Less CSS is always 1.
Build simple websites with Less CSS functions
Now it's time to combine everything you've learned and create a simple project using Less CSS. Create a directory and add index.htm and style.less files .
Open the index.htm file and add the following HTML code:
Document
The above code block has 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:
npm install -g less
Whenever you are ready to compile a .less file, just run the command below, making sure you specify the file to which the compiler should write the output.
lessc style.less style.css
In the style.less file, create two variables: container-width and container-bg-color to represent the width and background color of the "container" div, respectively.
@container-width: 50rem; @container-bg-color: yellow;
Next, create three variables namely: string, pattern, and replacement. . Then add styles for the "container" div and the h1 element.
@string: "Hello from the children of planet Earth!"; @pattern: "children of planet Earth!"; @replacement: "inhabitants of Pluto!"; .container{ width: @container-width; background-color: @container-bg-color; padding: if(@container-width > 30rem, range(20px, 80px, 20),""); border: solid; } h1:first-child::after{ content: replace(@string,@pattern,@replacement); }
In the code block above, the range() function sets the padding property on the "container" div. The Less compiler will compile the style.less file to the following:
.container { width: 50rem; background-color: yellow; padding: 20px 40px 60px 80px; border: solid; } h1:first-child::after { content: "Hello from the inhabitants of Pluto!"; }
When you open the index.htm file in your browser, the output looks like this:
Above is how to use functions in Less CSS . Hope the article is useful to you.
You should read it
- Function in programming C
- FUNCTION (Function) in SQL Server
- Save time with these text formatting functions in Microsoft Excel
- Function tmpfile () in C
- DAY function in SQL Server
- MIN function in SQL Server
- MAX function in SQL Server
- The function atexit () in C
- SUM function in SQL Server
- The ord () function in Python
- RIGHT function in SQL Server
- Int () function in Python
Maybe you are interested
We may be able to see the 'second moon' in the sky with the naked eye next May NASA reveals its latest snapshot of the Martian surface with a resolution of 1.8 billion pixels The most remote and least-populated places on Earth Discover human limits through 5 senses Is Proxima b our 'neighbor' planet? Why have scientists found Proxima b - '2nd Earth' until now?