Skip to content

Less Language Built In Functions

Mária Jurčovičová edited this page Sep 10, 2015 · 85 revisions

Less contains several build-in functions. Their names are case insensitive. If you use a function with wrong parameter, the function will report either an error or a warning.

Conflicts With CSS

Css3 contains both filter functions and general purpose functions. In addition, some browser vendors created their own functions on top of css3 specification. If less4j detects css3 function or vendor specific functions, it will evaluate only its parameters. The functions itself will be left unmodified.

Css3 functions detection:

  • If the function name contains either colon : or dot ., then it is considered a css3 function and is not evaluated.
  • Functions using named parameters (name=value) are considered css3 functions.
  • If there is a name clash between css3 and less function, less4j will use parameters types to distinguish between them.

Known name clashes:

  • saturate(<number> | <percentage>)
  • alpha(<number> | <percentage>)
  • contrast(<number> | <percentage>)

Example saturation:

@saturation: 10;
filter-1: saturate(@saturation); // css3 version takes number or percentage as parameter
filter-2: saturate(#29332f, 20%); // less version has two parameters

Compiles into:

filter-1: saturate(10); // parameter was evaluated, function was not
filter-2: #203c31; // function was evaluated

Strings

A list of supported strings and escaping functions ported into less4j.

###Escape The escape function escape(string) takes string as an argument and converts it into URI. Most special characters are encoded it into their UTF-8 %xxformat. However, the function does not encode characters that might be legitimately used in URI e.g., ,/?@&+'~!$. Space is encoded as %20.

Example: escape("question: ?") returns question%3A%20?;

Function behavior on non-string parameters is not defined. In practice, color arguments return undefined and all other kinds of arguments are returned back as their are.

###E The e function e(string) is very similar to values escaping. It takes string as a parameter and return it as is, but without quotes. Only strings, escaped values and numbers are allowed as parameters. Anything else returns an error.

Examples:

  • declaration: e("question: ?"); compiles into declaration: question: ?;
  • declaration: e("question: ?"); compiles into declaration: question: ?;
  • declaration: e(11+22); compiles into declaration: 33;

###Format The format function %("format", arguments ...) formats a string. The first argument is string with placeholders. All placeholders start with percentage symbol % followed by letter s,S,d,D,a, or A. Remaining arguments contain expressions to replace placeholders. If you need to print the percentage symbol, escape it by another percentage %%.

Use uppercase placeholders if you need to escape special characters into their utf-8 escape codes. The function escapes all special characters except ()'~!. Space is encoded as %20. Lowercase placeholders leave special characters as they are.

Placeholders:

  • d, D, a, A - can be replaced by any kind of argument (color, number, escaped value, expression, ...). If you use them in combination with string, the whole string will be used - including its quotes. However, the quotes are placed into the string as they are, they are not escaped by "/" nor anything similar.
  • s, S - can be replaced by any kind of argument. If you use it in combination with string, only the string value will be used - string quotes are omitted.

Sample input:

#format {
  format-a-d: %("repetitions: %a file: %d", 1 + 2, "directory/file.less");
  format-a-d-upper: %('repetitions: %A file: %D', 1 + 2, "directory/file.less");
  format-s: %("repetitions: %s file: %s", 1 + 2, "directory/file.less");
  format-s-upper: %('repetitions: %S file: %S', 1 + 2, "directory/file.less");
}

compiles into:

#format {
  format-a-d: "repetitions: 3 file: "directory/file.less"";
  format-a-d-upper: "repetitions: 3 file: %22directory%2Ffile.less%22";
  format-s: "repetitions: 3 file: directory/file.less";
  format-s-upper: 'repetitions: 3 file: directory%2Ffile.less';
}

Note: the function always returns double quoted string. However, the first argument of the format function can use any type of quotes and can represent also escaped value.

###Replace The replace function replace(target, pattern, replacement, [flags]) uses javascript regexp syntax to replace the regular expression pattern inside a target. The function accepts strings, escaped values and identifiers as its arguments.

Parameters:

  • target: target sequence to be modified,
  • pattern: regular expression to be replaced inside the target string,
  • replacement: replacement string,
  • flags: (optional) javascrit regexp flags.

Returns: string or escaped value or `` - the same type as input string

Example:

replace-first: replace("test a a a ", "a", "b");
replace-all: replace("test a a a ", "a", "b", 'g');

results in:

replace-first: "test b a a ";
replace-all: "test b b b ";

Math

###Percentage The function percentage(number) converts doubles into their corresponding percentage values. The parameter is multiplied by 100 and its units are changed into %. For example, the input 0 is converted to 0%, 0.3 is converted to 30% and so on. If the parameter is a string, the function attempts to convert it into a number first. If it does not succeed or a parameter is neither a number nor a string, the function returns NaN% and produces a warning.

Sample input:

#percentage {
  padding1: percentage(something); // NaN%;
  padding2: percentage("invalid"); // NaN%;
  padding3: percentage("0.5");  // 50%
  padding4: percentage(0.3); // 30%
  padding5: percentage(1%); // 100%
  padding6: percentage(1px); // 100%
  padding7: percentage(1+0.3); // 130%
}

compiles into:

#percentage {
  padding1: NaN%;
  padding2: NaN%;
  padding3: 50%;
  padding4: 30%;
  padding5: 100%;
  padding6: 100%;
  padding7: 130%;
}

###Round The function round(number) returns the closest integer to the argument. If it is a tie, the function rounds up. Units are are left as they are. If the parameter is not a number, the function reports an error.

Sample input:

#round {
  padding1: round(0.3);
  padding2: round(1.5%); 
  padding3: round(2.9px);
}

compiles into:

#round {
  padding1: 0;
  padding2: 2%;
  padding3: 3px;
}

Returns the closest long to the argument, with ties rounding up. ###Floor The function floor(number) returns the closest integer value lower then the argument. Units are are left as they are. If the parameter is not a number, the function reports an error.

Sample input:

#floor {
  padding1: floor(0.8);
  padding2: floor(1.5%); 
  padding3: floor(2.9px);
}

compiles into:

#floor {
  padding1: 0;
  padding2: 1%;
  padding3: 2px;
}

###Ceil The function ceil(number) returns the closest integer value higher then the argument. Units are are left as they are. If the parameter is not a number, the function reports an error.

Sample input:

#ceil {
  padding1: ceil(0.8);
  padding2: ceil(1.5%); 
  padding3: ceil(2.9px);
}

compiles into:

#ceil {
  padding1: 1;
  padding2: 2%;
  padding3: 3px;
}

###sqrt Calculates square root of a number. Keeps units as they are.

Parameters:

  • number: A floating point number.

Returns: number

Example:

sqrt(25cm)

Output:

5cm

Example:

sqrt(18.6%)

Output:

4.312771730569565%;

###abs Calculates absolute value of a number. Keeps units as they are.

Parameters:

  • number: A floating point number.

Returns: number

Example:

abs(25cm)

Output:

25cm

Example:

abs(-18.6%)

Output:

18.6%;

###sin Calculates sine function. Assumes radians on numbers without units.

Parameters:

  • number: A floating point number.

Returns: number

Example:

sin(1); // sine of 1 radian
sin(1deg); // sine of 1 degree
sin(1grad); // sine of 1 gradian

Output:

0.8414709848078965; // sine of 1 radian
0.01745240643728351; // sine of 1 degree
0.015707317311820675; // sine of 1 gradian

###asin Calculates arcsine (inverse of sine) function. Returns number in radians e.g. a number between -π/2 and π/2.

Parameters:

  • number: A floating point number from [-1, 1] interval.

Returns: number

Example:

asin(-0.8414709848078965)
asin(0) 
asin(2)

Output:

-1rad
0rad
NaNrad

###cos Calculates cosine function. Assumes radians on numbers without units.

Parameters:

  • number: A floating point number.

Returns: number

Example:

cos(1) // cosine of 1 radian
cos(1deg) // cosine of 1 degree
cos(1grad) // cosine of 1 gradian

Output:

0.5403023058681398 // cosine of 1 radian
0.9998476951563913 // cosine of 1 degree
0.9998766324816606 // cosine of 1 gradian

###acos Calculates arccosine (inverse of cosine) function. Returns number in radians e.g. a number between 0 and π.

Parameters:

  • number: A floating point number from [-1, 1] interval.

Returns: number

Example:

acos(0.5403023058681398)
acos(1) 
acos(2)

Output:

1rad
0rad
NaNrad

###tan Calculates tangent function. Assumes radians on numbers without units.

Parameters:

  • number: A floating point number.

Returns: number

Example:

tan(1) // tangent of 1 radian
tan(1deg) // tangent of 1 degree
tan(1grad) // tangent of 1 gradian

Output:

1.5574077246549023 // tangent of 1 radian
0.017455064928217585 // tangent of 1 degree
0.015709255323664916 // tangent of 1 gradian

###atan Calculates arctangent (inverse of tangent) function. Returns number in radians e.g. a number between -π/2 and π/2.

Parameters:

  • number: A floating point number.

Returns: number

Example:

atan(-1.5574077246549023)
atan(0)
round(atan(22), 6) // arctangent of 22 rounded to 6 decimal places

Output:

-1rad
0rad
1.525373rad;

###pi Returns π (pi);

Parameters:

  • none

Returns: number

Example:

pi()

Output:

3.141592653589793

###pow Returns the value of the first argument raised to the power of the second argument. Returned value has the same dimension as the first parameter and the dimension of the second parameter is ignored.

Parameters:

  • number: base -a floating point number.
  • number: exponent - a floating point number.

Returns: number

Example:

pow(0cm, 0px)
pow(25, -2)
pow(25, 0.5)
pow(-25, 0.5)
pow(-25%, -0.5)

Output:

1cm
0.0016
5
NaN
NaN%

###mod Returns the value of the first argument modulus second argument. Returned value has the same dimension as the first parameter, the dimension of the second parameter is ignored. The function is able to handle also negative and floating point numbers.

Parameters:

  • number: a floating point number.
  • number: a floating point number.

Returns: number

Example:

mod(0cm, 0px)
mod(11cm, 6px);
mod(-26%, -5);

Output:

NaNcm;
5cm
-1%;

###min Returns the lowest value found in arguments list. Arguments list can contain any expression type, however only numbers and sub-lists are considered. Strings, escapes, identifiers and other expression types are ignored.

The function extracts all numbers contained in its arguments. If the arguments list contains another list, numbers from embedded list are extracted too. Extracted numbers are converted into the same units, compared with each other and smallest one is returned as a result.

If the arguments list contains numbers with incompatible units, the function returns an error.

Returns: number

Example:

min(2mm, 1cm)
min(1deg 2rad, 1rad)
min(2cm, 2rad) //`cm` and `rad` can not be compared

Output:

2mm
1deg
!#error#! 

###max Returns the biggest value found in arguments list. Arguments list can contain any expression type, however only numbers and sub-lists are considered. Strings, escapes, identifiers and other expression types are ignored.

The function extracts all numbers contained in its arguments. If the arguments list contains another list, numbers from embedded list are extracted too. Extracted numbers are converted into the same units, compared with each other and highest one is returned as a result.

If the arguments list contains numbers with incompatible units, the function returns an error.

Returns: number

Example:

min(2mm, 1cm)
min(1deg 2rad, 1rad)
min(2cm, 2rad) //`cm` and `rad` can not be compared

Output:

1cm
2rad
!#error#! 

length

The function treats its first argument as a list and returns its length. Remaining arguments are ignored. If the first argument contains non-list (number, string, ...), the function returns 1. If it contains list, the function returns length of that list.

Returns: number

Example:

length("one") // returns 1
length(1 2 3) // returns 3
length(1 2, 3); // returns 2 - length of the first parameter "1 2" (!)
length(1, 2, 3); // returns 1 - length of the first parameter "1" (!)

Miscellaneous Functions

###Convert Converts numbers from one type into another. First argument contains number with units and second argument contains units. If both units are compatible, the number is converted. If they are not compatible, function returns first argument without modifying it.

Compatible unit groups:

  • lengths: m, cm, mm, in, pt and pc,
  • time: s and ms,
  • angle: rad, deg, grad and turn.

Parameters:

  • number: a floating point number with units.
  • identifier, string or escaped value: units

Returns: number

Example:

convert(9s, "ms")
convert(14cm, mm)
convert(8, mm) // incompatible unit types

Output:

9000ms
140mm
8

Unit

Returns number with different units. Only units are changed, number itself is not converted. The function assumes that second parameter contains valid unit type.

Parameters:

  • number: a floating point number with units.
  • identifier or escaped value: units.

Returns: number

Example:

unit(9s, ~"ms")
unit(-9, m)

Output:

9ms
-9m

Get-unit

Takes number as a parameter and returns its units.

Parameter:

  • number: a floating point number with units.

Example:

get-unit(10px); //returns px
get-unit(3); //returns an empty identifier
get-unit(5%); //returns %

Isunit

Returns true if a value is a number in specified units, false otherwise.

Parameters:

  • number - a value or variable being evaluated.
  • identifier or string or escaped value - a unit identifier (optionaly quoted) to test for.

Returns: true if value is a number in specified units, false otherwise.

Example:

isunit(32px, px) // returns true
isunit(32px, "px") // returns true
isunit(32, px) // returns false

Color

Converts a string or escaped value into a color. The input must contain either valid color name or color in hexadecimal representation.

Parameters:

  • identifier or escaped value with valid color name or color in hexadecimal representation.

Returns: color

Example:

color("#445566")
color(~"#123")
color("beige")

Output:

#445566
#112233
#f5f5dc

Note: less.js is does not support color names as parameters for this function.

Data-uri

The data-uri function reads a file and encodes its into css data uri form. It is useful when you want to save few http requests by embedding small pictures or other similar content into css. The function reads specified file, encodes it either into base64 or utf-8 and prints it as css data uri url("data:<mimetype>[;base64],<encoded file content>").

Mimetype parameter is optional. If it is missing, data-uri function will guess it from filename suffix. Text and svg files are encoded as utf-8 and anything else is encoded as base64.

If you provide mimetype manually, then the function will use base64 only if mimetype argument ends with ;base64. For example, image/jpeg;base64 is be encoded into base64 while text/html is encoded into utf-8.

The function is ie8 safe and will not embed resources larger then 38kb. Less.js has also an optional switch which allows turns on ie8 unsafe resources encoding. If you need such feature in less4j too, please open a new issue.

Parameters:

  • string: optional mimetype
  • string: relative path to resource

Example:

data-uri('../data/image.jpg'); //guesses image/jpeg;base64 mimetype (base64 encoding)
data-uri('../data/page.css'); //guesses text/css mimetype (utf-8 encoding)
data-uri('text/html', '../data/page.html'); // encodes into utf-8
data-uri('text/html;base64', '../data/page.html'); // encodes into base64

compiles into:

url("data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==");
url("data:text/css,.working%3Aafter%20%7B%20color%3A%20blue%3B%7D");
url("data:text/html,%3Ch1%3EThis%20page%20is%20100%25%20Awesome.%3C%2Fh1%3E%0A");
url('data:text/html;base64,PGgxPlRoaXMgcGFnZSBpcyAxMDAlIEF3ZXNvbWUuPC9oMT4K');

Image-size

The image-size function reads an image file and determines its width and height in pixels. It returns space separated list with two numbers. First element represents width and second represents length.

Supported image formats: bmp, gif, jpeg, png, wbmp.

Parameter:

  • string: relative path to image

Example:

image-size('../data/image.jpg'); 

compiles into:

10px 20px

Image-width

The image-width function reads an image file and determines its width in pixels. Supported image formats: bmp, gif, jpeg, png, wbmp.

Parameter:

  • string: relative path to image

Example:

image-width('../data/image.jpg'); 

compiles into:

10px

Image-length

The image-width function reads an image file and determines its length in pixels. Supported image formats: bmp, gif, jpeg, png, wbmp.

Parameter:

  • string: relative path to image

Example:

image-length('../data/image.jpg'); 

compiles into:

20px

Extract

Extracts i-th member of a list. TODO detailed description

Default

The default function default() can be used only inside mixin guards. It is documented on mixins page.

Color functions

svg-gradient

Svg-gradient function generates multi-stop svg gradients. First parameter specifies gradient type and direction and remaining parameters list colors and their positions. The position of first and last specified color are optional, remaining colors must have positions specified.

The direction is specified in the first parameter and must be one of to bottom, to right, to bottom right, to top right, ellipse or ellipse at center. It can have a form of either:

  • escaped value ~"to bottom",
  • space separated list of words to bottom.

The direction must be followed by two or more color stops. They can be supplied either inside a list or you can specify each color stops in separate argument.

Parameters

Parameters - colors stops in list:

  • escaped value or list of identifiers: direction
  • list pair: all colors and their positions in list

Parameters - each color stop is in separate parameter:

  • escaped value or list of identifiers: direction
  • color [percentage] pair: first color and its relative position (position is optional)
  • color percent pair: (optional) second color and its relative position
  • ...
  • color percent pair: (optional) n-th color and its relative position
  • color [percentage] pair: last color and its relative position (position is optional)

Returns: url with base64 encoded svg gradient.

Example

Example - colors stops in list:

div {
  @list: red, green 30%, blue;
  background-image: svg-gradient(to right, @list);
}

equivalent - each color stop is in separate parameter:

div {
  background-image: svg-gradient(to right, red, green 30%, blue);
}

both results in:

div {
  background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIHZpZXdCb3g9IjAgMCAxIDEiIHByZXNlcnZlQXNwZWN0UmF0aW89Im5vbmUiPjxsaW5lYXJHcmFkaWVudCBpZD0iZ3JhZGllbnQiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4MT0iMCUiIHkxPSIwJSIgeDI9IjEwMCUiIHkyPSIwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmMDAwMCIvPjxzdG9wIG9mZnNldD0iMzAlIiBzdG9wLWNvbG9yPSIjMDA4MDAwIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjMDAwMGZmIi8+PC9saW5lYXJHcmFkaWVudD48cmVjdCB4PSIwIiB5PSIwIiB3aWR0aD0iMSIgaGVpZ2h0PSIxIiBmaWxsPSJ1cmwoI2dyYWRpZW50KSIgLz48L3N2Zz4=')
}

Generated background image has red color on the left, green at 30% of its width and ends with a blue color:

gradient

Base64 encoded part contains following svg-gradient:

<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
    <linearGradient id="gradient" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="0%" stop-color="#ff0000"/>
        <stop offset="30%" stop-color="#008000"/>
        <stop offset="100%" stop-color="#0000ff"/>
    </linearGradient>
    <rect x="0" y="0" width="1" height="1" fill="url(#gradient)" />
</svg>

TODO detailed description to all of them

  • rgb,
  • rgba,
  • argb,
  • hsl,
  • hsla,
  • hsv,
  • hsva,
  • hue,
  • saturation,
  • lightness,
  • red,
  • green,
  • blue,
  • alpha,
  • luma,
  • saturate,
  • desaturate,
  • lighten,
  • darken,
  • fadein,
  • fadeout,
  • fade,
  • spin,
  • mix,
  • greyscale,
  • contrast,
  • multiply,
  • screen,
  • overlay,
  • softlight,
  • hardlight,
  • difference,
  • exclusion,
  • average,
  • negation,
  • tint,
  • shade,
  • hsvhue,
  • hsvsaturation,
  • hsvvalue,
  • luminance.