Open In App

Less.js Math abs() Function

Improve
Improve
Like Article
Like
Save
Share
Report

Less (Leaner Style Sheets) is an extension to normal CSS code which is basically used to enhance the abilities of normal CSS code and provide it superpowers.

The abs() function is a type of Math function in Less.js (which is basically used to perform mathematical operations). The abs() function is used to get the absolute value of the given argument which is to get the magnitude (without sign) of the argument. The unit of the given argument remains the same in the output, only the negative sign is removed (if it is present).

Syntax:

abs(number)

 

Parameters:

  • number: Any numeric value (with or without a unit). For example: 13px, -25%, -100 etc.

Example 1: In this example, we have set the font size of the p element using the abs() function on the variable @number as we don’t know whether it is negative or not but the font size must be positive only. 

HTML




<html lang="en">
<head>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
  
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>Less.js Math abs() Function</h3>
  
    <p>I am p tag</p>
</body>
</html>


styles.less: The LESS code is as follows.

CSS




@number: 15px + 2*(-14px) + 1px;
  
p {
    font-size: abs(@number);
}


Now, to compile the above LESS code to CSS code, run the following command:

lessc styles.less styles.css

The compiled CSS file comes to be:

styles.css: The output CSS file looks like the following.

CSS




p {
    font-size: 12px;
}


Output:

 

Example 2: In this example, we have a variable @negmargin which is storing a negative margin value. We have applied this negative margin by using CSS margin-top property for the h3 element. The absolute value of @negmargin is got by using the abs() function which is used for the CSS margin-bottom of the h3 element

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="/styles.css">
</head>
<body>
  
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>Less.js Math abs() Function</h3>
  
    <p>I am p tag</p>
</body>
</html>


styles.less: The LESS code looks like the following.

CSS




@negmargin: -20px;
  
h3 
{
    margin-top: @negmargin;
    margin-bottom: abs(@negmargin);
}


Now, to compile the above LESS code to CSS code, run the following command:

lessc styles.less styles.css

The compiled CSS file comes to be:

styles.css: The output CSS file looks like the following

CSS




h3 {
    margin-top: -20px;
    margin-bottom: 20px;
}


Output:

 

Reference: https://lesscss.org/functions/#math-functions-abs



Last Updated : 25 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads