LESS CSS | Built-in Functions

Built-in Functions in Less

Learner Style Sheet has several built-in functions as well. LESS maps JavaScript code with manipulation of values and uses predefined functions to manipulate HTML elements aspects in the style sheet.

  • Misc Functions

color

Parses a color. It is a string representing a color.

Example: color("#aaa");

image-size

Gets the image dimensions from a file.

Example: image-size("Myfile.png");

image-width

Gets the image width from a file. This function needs to be implemented by each environment. It is currently only available in the node environment.

Example: image-width("Myfile.png");

image-height

Gets the image height from a file. This function needs to be implemented by each environment. It is currently only available in the node environment.

Example: image-height("Myfile.png");

convert

Convert a number from one unit into another. The first argument contains a number with units and second argument contains units. If the units are compatible, the number is converted. If they are not compatible, the first argument is returned unmodified.

Compatible unit groups:

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

Example:

convert(19s, "ms")
convert(140cm, mm)
convert(28, mm) // incompatible unit types

data-uri

Data uri is uniform resource identifier (URI) schema which gets a resource inline on webpages.

Example:
data-uri('../data/image.jpg');

Output: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');

Output in browser: url('../data/image.jpg');

default

Available only inside guard conditions and returns true only if no other mixin matches, false otherwise.

Example:

.mixin(1) {x: 11}
.mixin(2) {y: 22}
.mixin(@x) when (default()) {z: @x}
div {
 .mixin(3);
}
div.special {
 .mixin(1);
 }
unit

Remove or change the unit of a dimension.

Example: unit(5, px) Output: 5px

get-unit

Returns units of a number. If the argument contains a number with units, the function returns its units. The argument without units results in an empty return value.

Example 1: get-unit(5px) Output: px

Example 2: get-unit(5) Output: //nothing

svg-gradient

svg-gradient is a transition of one color to another. It can add many colors to the same element. The position of first and last specified color are optional, remaining colors must have positions specified. The direction must be one of to bottom, to right, to bottom right, to top right, ellipse or ellipse at center. The direction can be specified as both escaped value ~'to bottom' and space separated list of words to bottom.

Example:
colors stops in list:

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

Returns one of two values depending on a condition.

Examples:

@some: foo;
div {
 margin: if((2 > 1), 0, 3px);
 color: if((iscolor(@some)), darken(@some, 10%), black);
 }
  • String Functions

escape

Applies URL-encoding to special characters found in the input string. These characters are not encoded: ,, /, ?, @, &, +, ‘, ~, ! and $. Most common encoded characters are: \<space\>, #, ^, (, ), {, }, |, :, >, <, ;, ], [ and =. Returns escaped string content without quotes.

Example:

escape('a=1')

Output:

a%3D1

[NOTE: if the parameter is not a string, output is not defined.]

e

String escaping. It expects string as a parameter and return its content as is, but without quotes. It can be used to output CSS value which is either not valid CSS syntax, or uses proprietary syntax which Less doesn’t recognize.

Example:

@mscode: "ms:alwaysHasItsOwnSyntax.For.Stuff()" 
filter: e(@mscode);

Output:

filter: ms:alwaysHasItsOwnSyntax.For.Stuff();
%format

The function %(string, 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 %%.

Example:

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");

Output:

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";
replace

Replaces a text within a string.

Example:

replace("Hello, Mars?", "Mars\?", "Earth!");
replace("One + one = 4", "one", "2", "gi");
replace('This is a string.', "(string)\.$", "new $1.");
replace(~"bar-1", '1', '2');

Output:

"Hello, Earth!";
"2 + 2 = 4";
'This is a new string.';
bar-2;
  • List Functions

extract

Returns the value at a specified position in a list.

Example: extract(8px dotted red, 2);

Output: dotted

Example:

@list: apple, pear, coconut, orange;
value: extract(@list, 3);

Output:

value: coconut;
length

Returns the number of elements in a value list.

Example: length(1px solid #0080ff);

Output: 3

Example:

@list: "banana", "tomato", "potato", "peach";
n: length(@list);

Output:

n: 4;
  • Math Functions

ceil

Rounds up to the next highest integer.

Example: ceil(2.4)

Output: 3

floor

Rounds down to the next lowest integer.

Example: floor(2.6)

Output: 2

percentage

Converts a floating point number into a percentage string.

Example: percentage(0.5)

Output: 50%

round

Applies rounding.

Example 1: round(1.67) Output: 2

Example 2: round(1.67, 1) Output: 1.7

sqrt

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

Example 1: sqrt(25cm)

Output: 5cm

Example 2: sqrt(18.6%)

Output: 4.312771730569565%;

abs

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

Example 1: abs(25cm)

Output: 25cm

Example 2: abs(-18.6%)

Output: 18.6%;

sin

Calculates sine function. Assumes radians on numbers without units.

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.

Example:

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

Output:

-1rad
0rad
NaNrad
cos

Calculates cosine function. Assumes radians on numbers without units.

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 π.

Example:

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

Output:

1rad
0rad
NaNrad
tan

Calculates tangent function. Assumes radians on numbers without units.

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.

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);

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.

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.

Example:

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

Output:

NaNcm;
5cm
-1%;
min

Returns the lowest of one or more values.

Example 1: min(5, 10);

Output: 5

Example 2: min(3px, 42px, 1px, 16px);

Output: 1px

max

Returns the highest of one or more values.

Example 1: max(5, 10);

Output: 10

Example 2: max(3%, 42%, 1%, 16%);

Output: 42%

  • Type Functions
Isnumber

Returns true if a value is a number, false otherwise.

Example:

isnumber(#ff0); // false
isnumber(blue); // false
isnumber("string"); // false
isnumber(1234); // true
isnumber(56px); // true
isnumber(7.8%); // true
isnumber(keyword); // false
isnumber(url(...)); // false
isstring

Returns true if a value is a string, false otherwise.

Example:

isstring(#ff0); // false
isstring(blue); // false
isstring("string"); // true
isstring(1234); // false
isstring(56px); // false
isstring(7.8%); // false
isstring(keyword); // false
isstring(url(...)); // false
iscolor

Returns true if a value is a color, false otherwise.

Example:

iscolor(#ff0); // true
iscolor(blue); // true
iscolor("string"); // false
iscolor(1234); // false
iscolor(56px); // false
iscolor(7.8%); // false
iscolor(keyword); // false
iscolor(url(...)); // false
iskeyword

Returns true if a value is a keyword, false otherwise.

Example:

iskeyword(#ff0); // false
iskeyword(blue); // false
iskeyword("string"); // false
iskeyword(1234); // false
iskeyword(56px); // false
iskeyword(7.8%); // false
iskeyword(keyword); // true
iskeyword(url(...)); // false
isurl

Returns true if a value is a url, false otherwise.

Example:

isurl(#ff0); // false
isurl(blue); // false
isurl("string"); // false
isurl(1234); // false
isurl(56px); // false
isurl(7.8%); // false
isurl(keyword); // false
isurl(url(...)); // true
ispixel

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

Example:

ispixel(#ff0); // false
ispixel(blue); // false
ispixel("string"); // false
ispixel(1234); // false
ispixel(56px); // true
ispixel(7.8%); // false
ispixel(keyword); // false
ispixel(url(...)); // false
isem

Returns true if a value is an em value, false otherwise.

Example:

isem(#ff0); // false
isem(blue); // false
isem("string"); // false
isem(1234); // false
isem(56px); // false
isem(7.8em); // true
isem(keyword); // false
isem(url(...)); // false
ispercentage

Returns true if a value is a percentage value, false otherwise.

Example:

ispercentage(#ff0); // false
ispercentage(blue); // false
ispercentage("string"); // false
ispercentage(1234); // false
ispercentage(56px); // false
ispercentage(7.8%); // true
ispercentage(keyword); // false
ispercentage(url(...)); // false
isunit

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

Example:

isunit(11px, px); // true
isunit(2.2%, px); // false
isunit(33px, rem); // false
isunit(4rem, rem); // true
isunit(56px, "%"); // false
isunit(7.8%, '%'); // true
isunit(1234, em); // false
isunit(#ff0, pt); // false
isunit("mm", mm); // false
isrules

Returns true if a value is a ruleset, false otherwise.

Example:

@rules: {
 color: red;
}

isruleset(@rules); // true
isruleset(#ff0); // false
isruleset(blue); // false
isruleset("string"); // false
isruleset(1234); // false
isruleset(56px); // false
isruleset(7.8%); // false
isruleset(keyword); // false
isruleset(url(...)); // false
  • Color Definition Functions

rgb

Creates an opaque color object from decimal red, green and blue (RGB) values. Literal color values in standard HTML/CSS formats may also be used to define colors, for example #ff0000.

Example: rgb(90, 129, 32)

Output: #5a8120

[NOTE: An integer 0-255 or percentage 0-100% is used as parameter value in the function.]

rgba

Creates a transparent color object from decimal red, green, blue and alpha (RGBA) values.

Example: rgba(90, 129, 32, 0.5)

Output: rgba(90, 129, 32, 0.5)

argb

Creates a hex representation of a color in #AARRGGBB format (NOT #RRGGBBAA!). This format is used in Internet Explorer, and .NET and Android development.

Example: argb(rgba(90, 23, 148, 0.5));

Output: #805a1794

hsl

Creates an opaque color object from hue, saturation and lightness (HSL) values.

hue: An integer 0-360 representing degrees.
saturation: A percentage 0-100% or number 0-1.
lightness: A percentage 0-100% or number 0-1.

Example: hsl(90, 100%, 50%)

Output: #80ff00

hsla

Creates a transparent color object from hue, saturation, lightness and alpha (HSLA) values.

hue: An integer 0-360 representing degrees.
saturation: A percentage 0-100% or number 0-1.
lightness: A percentage 0-100% or number 0-1.
alpha: A percentage 0-100% or number 0-1.

Example: hsla(90, 100%, 50%, 0.5)

Output: rgba(128, 255, 0, 0.5)

hsv

Creates an opaque color object from hue, saturation and value (HSV) values. Note that this is a color space available in Photoshop, and is not the same as hsl.

hue: An integer 0-360 representing degrees.
saturation: A percentage 0-100% or number 0-1.
value: A percentage 0-100% or number 0-1.

Example: hsv(90, 100%, 50%)

Output: #408000

hsva

Creates a transparent color object from hue, saturation, value and alpha (HSVA) values. Note that this is not the same as hsla, and is a color space available in Photoshop.

hue: An integer 0-360 representing degrees.
saturation: A percentage 0-100% or number 0-1.
value: A percentage 0-100% or number 0-1.
alpha: A percentage 0-100% or number 0-1.

Example: hsva(90, 100%, 50%, 0.5)

Output: rgba(64, 128, 0, 0.5)

  • Color Channel Functions

hue

Extracts the hue channel of a color object in the HSL color space.

Example: hue(hsl(90, 100%, 50%))

Output: 90

saturation

Extracts the saturation channel of a color object in the HSL color space.

Example: saturation(hsl(90, 100%, 50%))

Output: 100%

lightness

Extracts the lightness channel of a color object in the HSL color space.

Example: lightness(hsl(90, 100%, 50%))

Output: 50%

hsvhue

Extracts the hue channel of a color object in the HSV color space.

Example: hsvhue(hsv(90, 100%, 50%))

Output: 90

hsvsaturation

Extracts the saturation channel of a color object in the HSV color space.

Example: hsvsaturation(hsv(90, 100%, 50%))

Output: 100%

hsvvalue

Extracts the value channel of a color object in the HSV color space.

Example: hsvvalue(hsv(90, 100%, 50%))

Output: 50%

red

Extracts the red channel of a color object.

Example: red(rgb(10, 20, 30))

Output: 10

green

Extracts the green channel of a color object.

Example: green(rgb(10, 20, 30))

Output: 20

blue

Extracts the blue channel of a color object.

Example: blue(rgb(10, 20, 30))

Output: 30

alpha

Extracts the alpha channel of a color object.

Example: alpha(rgba(10, 20, 30, 0.5))

Output: 0.5

luma

Calculates the luma (perceptual brightness) of a color object. Uses SMPTE C / Rec. 709 coefficients, as recommended in WCAG 2.0. This calculation is also used in the contrast function.

Example: luma(rgb(100, 200, 30))

Output: 44%

luminance

Calculates the value of the luma without gamma correction.

Example: luminance(rgb(100, 200, 30))

Output: 65%

  • Color Operation Functions

saturate

Increase the saturation of a color in the HSL color space by an absolute amount.

Example: saturate(hsl(90, 80%, 50%), 20%)

Output: #80ff00 // hsl(90, 100%, 50%)

desaturate

Decrease the saturation of a color in the HSL color space by an absolute amount.

Example: desaturate(hsl(90, 80%, 50%), 20%)

Output: #80cc33 // hsl(90, 60%, 50%)

lighten

Increase the lightness of a color in the HSL color space by an absolute amount.

Example: lighten(hsl(90, 80%, 50%), 20%)

Output: #b3f075 // hsl(90, 80%, 70%)

darken

Decrease the lightness of a color in the HSL color space by an absolute amount.

Example: darken(hsl(90, 80%, 50%), 20%)

Output: #4d8a0f // hsl(90, 80%, 30%)

fadein

Decrease the transparency (or increase the opacity) of a color, making it more opaque. Has no effect on opaque colors. To fade in the other direction use fadeout.

Example: fadein(hsla(90, 90%, 50%, 0.5), 10%)

Output: rgba(128, 242, 13, 0.6) // hsla(90, 90%, 50%, 0.6)

fadeout

Increase the transparency (or decrease the opacity) of a color, making it less opaque. To fade in the other direction use fadein.

Example: fadeout(hsla(90, 90%, 50%, 0.5), 10%)

Output: rgba(128, 242, 13, 0.4) // hsla(90, 90%, 50%, 0.4)

fade

Set the absolute opacity of a color. Can be applied to colors whether they already have an opacity value or not.

Example: fade(hsl(90, 90%, 50%), 10%)

Output: rgba(128, 242, 13, 0.1) //hsla(90, 90%, 50%, 0.1)

spin

Rotate the hue angle of a color in either direction. While the angle range is 0-360, it applies a mod 360 operation, so you can pass in much larger (or negative) values and they will wrap around.

Example:

spin(hsl(10, 90%, 50%), 30)
spin(hsl(10, 90%, 50%), -30)

Output:

#f2a60d // hsl(40, 90%, 50%)
#f20d59 // hsl(340, 90%, 50%)
mix

Mix two colors together in variable proportion. Opacity is included in the calculations.

Example:

mix(#ff0000, #0000ff, 50%)
mix(rgba(100,0,0,1.0), rgba(0,100,0,0.5), 50%)

Output:

#800080
rgba(75, 25, 0, 0.75)
tint

Mix color with white in variable proportion. It is the same as calling mix(#ffffff, @color, @weight)

Example:

no-alpha: tint(#007fff, 50%); 
with-alpha: tint(rgba(00,0,255,0.5), 50%);

Output:

no-alpha: #80bfff;
with-alpha: rgba(191, 191, 255, 0.75);
shade

Mix color with black in variable proportion. It is the same as calling mix(#000000, @color, @weight)

Example:

no-alpha: shade(#007fff, 50%); 
with-alpha: shade(rgba(00,0,255,0.5), 50%);

Output:

no-alpha: #004080;
with-alpha: rgba(0, 0, 64, 0.75);
greyscale

Remove all saturation from a color in the HSL color space; the same as calling desaturate(@color, 100%).

Example: greyscale(hsl(90, 90%, 50%))

Output: #808080 // hsl(90, 0%, 50%)

contrast

Choose which of two colors provides the greatest contrast with another. This is useful for ensuring that a color is readable against a background, which is also useful for accessibility compliance. This function works the same way as the contrast function in Compass for SASS.

Example:

p {
 a: contrast(#bbbbbb);
 b: contrast(#222222, #101010);
 c: contrast(#222222, #101010, #dddddd);
 d: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 30%);
 e: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 80%);
}

Output:

p {
 a: #000000 // black
 b: #ffffff // white
 c: #dddddd
 d: #000000 // black
 e: #ffffff // white
}

These examples use the above calculated colors for background and foreground; you can see that you never end up with white-on-white, nor black-on-black, though it’s possible to use the threshold to permit lower-contrast outcomes.

  • Color Blending Functions

multiply

Multiply two colors. Corresponding RGB channels from each of the two colors are multiplied together then divided by 255. The result is a darker color.

Example:

multiply(#ff6600, #000000);
screen

Do the opposite of multiply. The result is a brighter color.

Example:

screen(#ff6600, #000000);
overlay

Combines the effects of both multiply and screen. Conditionally make light channels lighter and dark channels darker. Note: The results of the conditions are determined by the first color parameter.

Example:

overlay(#ff6600, #000000);
softlight

Similar to overlay but avoids pure black resulting in pure black, and pure white resulting in pure white.

Example:

softlight(#ff6600, #000000);
hardlight

The same as overlay but with the color roles reversed.

Example:

hardlight(#ff6600, #000000);
difference

Subtracts the second color from the first color on a channel-by-channel basis. Negative values are inverted. Subtracting black results in no change; subtracting white results in color inversion.

Example:

difference(#ff6600, #000000);
exclusion

A similar effect to difference with lower contrast.

Example:

exclusion(#ff6600, #000000);
average

Compute the average of two colors on a per-channel (RGB) basis.

Example:

average(#ff6600, #000000);
negation

Do the opposite effect to difference. The result is a brighter color. Note: The opposite effect doesn’t mean the inverted effect as resulting from an addition operation.

Example:

negation(#ff6600, #000000);

 

Hope this article was helpful. We would love to hear from you. Must share your views in comments below.

Keep visiting Tech Blog to stay updated with all our latest technology blog posts.

1 thought on “LESS CSS | Built-in Functions”

  1. I’m still learning from you, while I’m trying to reach my goals. I certainly love reading all that is written on your site.Keep the information coming. I liked it!

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.