Less (Leaner Style Sheets) is an extension to normal CSS which is basically used to enhance the abilities of normal CSS code and provide it superpowers.
The percentage() function is a type of Math function in Less.js (which is basically used to perform mathematical operations). The percentage() function is used to convert any numeric floating point value to a percentage value. For example, using the percentage function on a value of 0.5 will return 50% as the output.
Parameters:
- number: Any numeric floating point value. For example: 0.3, 13, 2.5 etc.
Syntax:
percentage(number)
Example 1: In this example, we want that the width of the container becomes equal to 25% but we have a variable, @width, which is storing the value 0.25. We use the percentage() function on this and apply the width to the container.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Less.js Math percentage() Function</ title > < link rel = "stylesheet" href = "styles.css" > </ head > < body > < div class = "container" > < h1 style = "color: green;" >neveropen</ h1 > < h3 >Less.js Math percentage() Function</ h3 > </ div > </ body > </ html > |
styles.less: The LESS code is as follows.
CSS
@ width : 0.25 ; .container { border : 2px solid black ; width : percentage(@width); } |
Syntax: To compile the above LESS code into normal CSS, run the following command.
lessc styles.less styles.css
styles.css: The output CSS file looks like the following
CSS
.container { border : 2px solid black ; width : 25% ; } |
Output:
Example 2: In this example, we have calculated the sine of 20 degrees using the sin() function of Less.js. We have converted the value to a percentage value and applied it to the height and width of the container class.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta http-equiv = "X-UA-Compatible" content = "IE=edge" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Less.js Math percentage() Function</ title > < link rel = "stylesheet" href = "/styles.css" > </ head > < body > < div class = "container" > < h1 style = "color: green;" > neveropen </ h1 > < h3 >Less.js Math percentage() Function</ h3 > </ div > </ body > </ html > |
styles.less: The LESS code is as follows.
CSS
@value: sin( 20 deg); body { height : 100 vh; } .container { border : 2px solid black ; height : percentage(@value); width : percentage(@value); } |
Syntax: To compile the above LESS code into normal CSS, run the following command.
lessc styles.less styles.css
styles.css: The output CSS file looks like the following.
CSS
body { height : 100 vh; } .container { border : 2px solid black ; height : 34.20201433% ; width : 34.20201433% ; } |
Output:
Reference: https://lesscss.org/functions/#math-functions-percentage