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
May be interested
- How to Create and Call PHP Functionsperhaps you have learned the basics of writing php scripts. but sometimes your code may be long and repetitive. php functions are a flexible and easy way to consolidate code. this tutorial will you teach the basics of php functions. (note:...
- Python locals () functionthe locals () function in python returns a dictionary containing the variables defined in the local namespace.
- Functions are fields in Golangin golang, you can define functions as fields in a struct. this feature allows you to bind behavior (methods) directly to data types.
- Date time functions in Excelexcel supports you to process and calculate quickly with the functions that excel provides such as calculation functions, date functions ... one of them is the function of time to help you handle the prices. time value: hour, minute, second conveniently
- The MIN and MAX functions (the smallest and largest value functions) in Excelthe function to return the maximum value (max) and the function to return the minimum value (min) are two common statistical functions used by a lot of people in the process of manipulating and processing data in excel.
- 8 little-known Excel functions that can save you a lot of workeven seasoned excel users often find themselves stuck performing tasks manually that could be automated with a few clever functions.
- Python functions are user definedbesides the built-in python functions, you can also define python functions yourself, these functions are called user-defined functions (python). what are the benefits of using these self-defined functions, the best way to define functions in python, we'll learn in this python lesson.
- Tips for working with functions in Excelfunctions that work with excel functions functions are predefined formulas for performing specific calculations, or for manipulating spreadsheets.
- 8 useful functions in Google Sheets you may not knowin this article, i will show 10 useful functions for google sheets spreadsheets that you should know such as vlookup, countif, sumif, join, index,... in addition, you can refer to these functions. and other tips follow the link in the article.
- Logical functions (logical) in Excellogical functions are used a lot during data processing in excel. the article summarizes the syntax and functions of functions in logical function groups in excel.