Less
Logical Functions
if
Returns one of two values depending on a condition.
Parameters:
-
condition
: A boolean expression -
value1
: A value returned ifcondition
is true. -
value2
: A value returned ifcondition
is not true.
Released: v3.0.0 Updated: v3.6.0
Examples:
@some: foo; div { margin: if((2 > 1), 0, 3px); color: if((iscolor(@some)), @some, black); }
Result:
div { margin: 0; color: black; }
Notes: A boolean expression supported as the conditional
parameter are the same as of Guard Statements.
if(not (true), foo, bar); if((true) and (2 > 1), foo, bar); if((false) or (isstring("boo!")), foo, bar);
Note: before Less 3.6, the condition required a set of parentheses.
if(2 > 1, blue, green); // Causes an error in 3.0-3.5.3 if((2 > 1), blue, green); // Ok 3.0+
boolean
Evaluates to true or false
You can "store" a boolean test for later evaluation in a guard or if()
.
Parameters:
-
condition
: A boolean expression
Released: v3.0.0 Updated: v3.6.0
Examples:
@bg: black; @bg-light: boolean(luma(@bg) > 50%); div { background: @bg; color: if(@bg-light, black, white); }
Result:
div { background: black; color: white; }
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=
.
Parameters: string
: a string to escape.
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. The current implementation returns undefined
on color and unchanged input on any other kind of argument. This behavior should not be relied on and may change in the future.
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.
Parameters: string
- a string to escape.
Returns: string
- the escaped string, without quotes.
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 %%
.
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 expression. If you use it with string, only the string value is used - quotes are omitted.
Parameters:
-
string
: format string with placeholders, -
anything
* : values to replace placeholders.
Returns: formatted string
.
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.
Released v1.7.0
Parameters:
-
string
: The string to search and replace in. -
pattern
: A string or regular expression pattern to search for. -
replacement
: The string to replace the matched pattern with. -
flags
: (Optional) regular expression flags.
Returns: a string with the replaced values.
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');
Result:
"Hello, Earth!"; "2 + 2 = 4"; 'This is a new string.'; bar-2;
List Functions
length
Returns the number of elements in a value list.
Parameters
-
list
- a comma or space separated list of values.
Example: length(1px solid #0080ff);
Output: 3
Example:
@list: "banana", "tomato", "potato", "peach"; n: length(@list);
Output:
n: 4;
extract
Returns the value at a specified position in a list.
Parameters
-
list
- a comma or space separated list of values. -
index
- an integer that specifies a position of a list element to return.
Example: extract(8px dotted red, 2);
Output: dotted
Example:
@list: apple, pear, coconut, orange; value: extract(@list, 3);
Output:
value: coconut;
range
Released v3.9.0
Generate a list spanning a range of values
Parameters
-
start
- (optional) The start value e.g. 1 or 1px -
end
- The end value e.g. 5px -
step
- (optional) The amount to increment by
Examples:
value: range(4);
Outputs:
value: 1 2 3 4;
The output of each value in the range will be the same unit as the end
value. For example:
value: range(10px, 30px, 10);
Outputs:
value: 10px 20px 30px;
each
Released v3.7.0
Bind the evaluation of a ruleset to each member of a list.
Parameters
-
list
- a comma or space separated list of values. -
rules
- An anonymous ruleset/mixin
Example:
@selectors: blue, green, red; each(@selectors, { .sel-@{value} { a: b; } });
Outputs:
.sel-blue { a: b; } .sel-green { a: b; } .sel-red { a: b; }
By default, each ruleset is bound, per list member, to a @value
, @key
, and @index
variable. For most lists, @key
and @index
will be assigned the same value (numerical position, 1-based). However, you can also use rulesets themselves as structured lists. As in:
@set: { one: blue; two: green; three: red; } .set { each(@set, { @{key}-@{index}: @value; }); }
This will output:
.set { one-1: blue; two-2: green; three-3: red; }
Since you can, of course, call mixins with guards for each ruleset call, this makes each()
a very powerful function.
Setting variable names in each()
You don't have to use @value
, @key
, and @index
in your each()
function. In Less 3.7, with the each()
function, Less is introducing the concept of anonymous mixins, which may expand to other parts of the syntax at a later date.
An anonymous mixin uses the form of #()
or .()
starting with .
or #
just like a regular mixin would. In each()
, you can use it like this:
.set-2() { one: blue; two: green; three: red; } .set-2 { // Call mixin and iterate each rule each(.set-2(), .(@v, @k, @i) { @{k}-@{i}: @v; }); }
This outputs, as expected:
.set-2 { one-1: blue; two-2: green; three-3: red; }
The each()
function will take the variable names defined in the anonymous mixin and bind them to the @value
, @key
and @index
values, in that order. If you only write each(@list, #(@value) {})
, then neither @key
nor @index
will be defined.
Creating a for
loop using range
and each
Requires Less v3.9.0
You can emulate a for
loop simply by generating a numerical list and using each
to expand it to a ruleset.
Example:
each(range(4), { .col-@{value} { height: (@value * 50px); } });
Outputs:
.col-1 { height: 50px; } .col-2 { height: 100px; } .col-3 { height: 150px; } .col-4 { height: 200px; }
Math Functions
ceil
Rounds up to the next highest integer.
Parameters: number
- a floating point number.
Returns: integer
Example: ceil(2.4)
Output: 3
floor
Rounds down to the next lowest integer.
Parameters: number
- a floating point number.
Returns: integer
Example: floor(2.6)
Output: 2
percentage
Converts a floating point number into a percentage string.
Parameters: number
- a floating point number.
Returns: number
Example: percentage(0.5)
Output: 50%
round
Applies rounding.
Parameters:
-
number
: A floating point number. -
decimalPlaces
: Optional: The number of decimal places to round to. Defaults to 0.
Returns: number
Example: round(1.67)
Output: 2
Example: round(1.67, 1)
Output: 1.7
sqrt
Calculates square root of a number. Keeps units as they are.
Parameters: number
- 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 #1: abs(25cm)
Output: 25cm
Example #2: 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
- 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 of one or more values.
Parameters: value1, ..., valueN
- one or more values to compare.
Returns: the lowest value.
Example: min(5, 10);
Output: 5
Example: min(3px, 42px, 1px, 16px);
Output: 1px
max
Returns the highest of one or more values.
Parameters: value1, ..., valueN
- one or more values to compare.
Returns: the highest value.
Example: max(5, 10);
Output: 10
Example: max(3%, 42%, 1%, 16%);
Output: 42%
Type Functions
isnumber
Returns true
if a value is a number, false
otherwise.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if value is a pixel, 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters: value
- a value or variable being evaluated.
Returns: true
if 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.
Parameters:
-
value
- a value or variable being evaluated. -
unit
- a unit identifier (optionally quoted) to test for.
Returns: true
if 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
isruleset
Returns true
if a value is a ruleset, false
otherwise.
Parameters:
-
value
- a variable being evaluated.
Returns: true
if 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
Misc Functions
color
Parses a color, so a string representing a color becomes a color.
Parameters: string
: a string of the specified color.
Returns: color
Example: color("#aaa");
Output: #aaa
image-size
Gets the image dimensions from a file.
Parameters: string
: the file to get the dimensions for.
Returns: dimension
Example: image-size("file.png");
Output: 10px 10px
Note: this function needs to be implemented by each environment. It is currently only available in the node environment.
Added in: v2.2.0
image-width
Gets the image width from a file.
Parameters: string
: the file to get the dimensions for.
Returns: dimension
Example: image-width("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only available in the node environment.
Added in: v2.2.0
image-height
Gets the image height from a file.
Parameters: string
: the file to get the dimensions for.
Returns: dimension
Example: image-height("file.png");
Output: 10px
Note: this function needs to be implemented by each environment. It is currently only available in the node environment.
Added in: v2.2.0
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.
See unit for changing the unit without conversion.
Compatible unit groups:
- lengths:
m
,cm
,mm
,in
,pt
andpc
, - time:
s
andms
, - angle:
rad
,deg
,grad
andturn
.
Parameters:
-
number
: a floating point number with units. -
identifier
,string
orescaped value
: units
Returns: number
Example:
convert(9s, "ms") convert(14cm, mm) convert(8, mm) // incompatible unit types
Output:
9000ms 140mm 8
data-uri
Inlines a resource and falls back to url()
if the ieCompat option is on and the resource is too large, or if you use the function in the browser. If the MIME type is not given then node uses the mime package to determine the correct mime type.
Parameters:
-
mimetype
: (Optional) A MIME type string. -
url
: The URL of the file to inline.
If there is no mimetype, data-uri function guesses it from filename suffix. Text and svg files are encoded as utf-8 and anything else is encoded as base64.
If user provided mimetype, the function uses base64 if mimetype argument ends with ;base64. For example, image/jpeg;base64
is encoded into base64 while text/html
is encoded into utf-8.
Example: data-uri('../data/image.jpg');
Output: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Output in browser: url('../data/image.jpg');
Example: data-uri('image/jpeg;base64', '../data/image.jpg');
Output: url('data:image/jpeg;base64,bm90IGFjdHVhbGx5IGEganBlZyBmaWxlCg==');
Example: data-uri('image/svg+xml;charset=UTF-8', 'image.svg');
Output: url("data:image/svg+xml;charset=UTF-8,%3Csvg%3E%3Ccircle%20r%3D%229%22%2F%3E%3C%2Fsvg%3E");
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); }
Output:
div { z: 3; } div.special { x: 11; }
It is possible to use the value returned by default
with guard operators. For example .mixin() when not(default()) {}
will match only if there's at least one more mixin definition that matches.mixin()
call:
.mixin(@value) when (ispixel(@value)) {width: @value} .mixin(@value) when not(default()) {padding: (@value / 5)} div-1 { .mixin(100px); } div-2 { /* ... */ .mixin(100%); }
result:
div-1 { width: 100px; padding: 20px; } div-2 { /* ... */ }
It is allowed to make multiple default()
calls in the same guard condition or in a different conditions of a mixins with the same name:
div { .m(@x) when (default()), not(default()) {always: @x} .m(@x) when (default()) and not(default()) {never: @x} .m(1); // OK }
However Less will throw a error if it detects a potential conflict between multiple mixin definitions using default()
:
div { .m(@x) when (default()) {} .m(@x) when not(default()) {} .m(1); // Error }
In above example it is impossible to determine what value each default()
call should return since they recursively depend on each other.
Advanced multiple default()
usage:
.x { .m(red) {case-1: darkred} .m(blue) {case-2: darkblue} .m(@x) when (iscolor(@x)) and (default()) {default-color: @x} .m('foo') {case-1: I am 'foo'} .m('bar') {case-2: I am 'bar'} .m(@x) when (isstring(@x)) and (default()) {default-string: and I am the default} &-blue {.m(blue)} &-green {.m(green)} &-foo {.m('foo')} &-baz {.m('baz')} }
Result:
.x-blue { case-2: #00008b; } .x-green { default-color: #008000; } .x-foo { case-1: I am 'foo'; } .x-baz { default-string: and I am the default; }
The default
function is available as a Less built-in function only inside guard expressions. If used outside of a mixin guard condition it is interpreted as a regular CSS value:
Example:
div { foo: default(); bar: default(42); }
Result:
div { foo: default(); bar: default(42); }
unit
Remove or change the unit of a dimension
Parameters:
-
dimension
: A number, with or without a dimension. -
unit
: (Optional) the unit to change to, or if omitted it will remove the unit.
See convert for changing the unit with conversion.
Example: unit(5, px)
Output: 5px
Example: unit(5em)
Output: 5
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.
Parameters:
-
number
: a number with or without units.
Example: get-unit(5px)
Output: px
Example: get-unit(5)
Output: //nothing
svg-gradient
Generates multi-stop svg gradients.
Svg-gradient function generates multi-stop svg gradients. It must have at least three parameters. 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 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
.
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 - colors stops in list:
-
escaped value
orlist of identifiers
: direction -
list
- all colors and their positions in list
Parameters - color stops in arguments:
-
escaped value
orlist 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 "URI-Encoded" svg gradient.
Example - colors stops in list:
div { @list: red, green 30%, blue; background-image: svg-gradient(to right, @list); }
equivalent - color stops in arguments:
div { background-image: svg-gradient(to right, red, green 30%, blue); }
both result in:
div { background-image: url('data:image/svg+xml,%3C%3Fxml%20version%3D%221.0%22%20%3F%3E%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20width%3D%22100%25%22%20height%3D%22100%25%22%20viewBox%3D%220%200%201%201%22%20preserveAspectRatio%3D%22none%22%3E%3ClinearGradient%20id%3D%22gradient%22%20gradientUnits%3D%22userSpaceOnUse%22%20x1%3D%220%25%22%20y1%3D%220%25%22%20x2%3D%22100%25%22%20y2%3D%220%25%22%3E%3Cstop%20offset%3D%220%25%22%20stop-color%3D%22%23ff0000%22%2F%3E%3Cstop%20offset%3D%2230%25%22%20stop-color%3D%22%23008000%22%2F%3E%3Cstop%20offset%3D%22100%25%22%20stop-color%3D%22%230000ff%22%2F%3E%3C%2FlinearGradient%3E%3Crect%20x%3D%220%22%20y%3D%220%22%20width%3D%221%22%20height%3D%221%22%20fill%3D%22url(%23gradient)%22%20%2F%3E%3C%2Fsvg%3E'); }
Note: in versions before 2.2.0 the result is base64
encoded .
Generated background image has red color on the left, green at 30% of its width and ends with a blue color. 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>
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
.
Parameters:
-
red
: An integer 0-255 or percentage 0-100%. -
green
: An integer 0-255 or percentage 0-100%. -
blue
: An integer 0-255 or percentage 0-100%.
Returns: color
Example: rgb(90, 129, 32)
Output: #5a8120
rgba
Creates a transparent color object from decimal red, green, blue and alpha (RGBA) values.
Parameters:
-
red
: An integer 0-255 or percentage 0-100%. -
green
: An integer 0-255 or percentage 0-100%. -
blue
: An integer 0-255 or percentage 0-100%. -
alpha
: A number 0-1 or percentage 0-100%.
Returns: color
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.
Parameters: color
, color object.
Returns: string
Example: argb(rgba(90, 23, 148, 0.5));
Output: #805a1794
hsl
Creates an opaque color object from hue, saturation and lightness (HSL) values.
Parameters:
-
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.
Returns: color
Example: hsl(90, 100%, 50%)
Output: #80ff00
This is useful if you want to create a new color based on another color's channel, forExample: @new: hsl(hue(@old), 45%, 90%);
@new
will have @old
's hue, and its own saturation and lightness.
hsla
Creates a transparent color object from hue, saturation, lightness and alpha (HSLA) values.
Parameters:
-
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.
Returns: color
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
.
Parameters:
-
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.
Returns: color
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.
Parameters:
-
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.
Returns: color
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.
Parameters: color
- a color object.
Returns: integer
0-360
Example: hue(hsl(90, 100%, 50%))
Output: 90
saturation
Extracts the saturation channel of a color object in the HSL color space.
Parameters: color
- a color object.
Returns: percentage
0-100
Example: saturation(hsl(90, 100%, 50%))
Output: 100%
lightness
Extracts the lightness channel of a color object in the HSL color space.
Parameters: color
- a color object.
Returns: percentage
0-100
Example: lightness(hsl(90, 100%, 50%))
Output: 50%
hsvhue
Extracts the hue channel of a color object in the HSV color space.
Parameters: color
- a color object.
Returns: integer
0-360
Example: hsvhue(hsv(90, 100%, 50%))
Output: 90
hsvsaturation
Extracts the saturation channel of a color object in the HSV color space.
Parameters: color
- a color object.
Returns: percentage
0-100
Example: hsvsaturation(hsv(90, 100%, 50%))
Output: 100%
hsvvalue
Extracts the value channel of a color object in the HSV color space.
Parameters: color
- a color object.
Returns: percentage
0-100
Example: hsvvalue(hsv(90, 100%, 50%))
Output: 50%
red
Extracts the red channel of a color object.
Parameters: color
- a color object.
Returns: float
0-255
Example: red(rgb(10, 20, 30))
Output: 10
green
Extracts the green channel of a color object.
Parameters: color
- a color object.
Returns: float
0-255
Example: green(rgb(10, 20, 30))
Output: 20
blue
Extracts the blue channel of a color object.
Parameters: color
- a color object.
Returns: float
0-255
Example: blue(rgb(10, 20, 30))
Output: 30
alpha
Extracts the alpha channel of a color object.
Parameters: color
- a color object.
Returns: float
0-1
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.
Before v1.7.0 the luma was calculated without gamma correction, use the luminance function to calculate these "old" values.
Parameters: color
- a color object.
Returns: percentage
0-100%
Example: luma(rgb(100, 200, 30))
Output: 44%
luminance
Calculates the value of the luma without gamma correction (this function was named luma
before v1.7.0)
Parameters: color
- a color object.
Returns: percentage
0-100%
Example: luminance(rgb(100, 200, 30))
Output: 65%
Color Operation Functions
Color operations generally take parameters in the same units as the values they are changing, and percentages are handled as absolutes, so increasing a 10% value by 10% results in 20%. Set the option method parameter to relative for relative percentages. When using relative percentages increasing a 10% value by 10% results in 11%. Values are clamped to their allowed ranges; they do not wrap around. Where return values are shown, we've used formats that make it clear what each function has done, in addition to the hex versions that you will usually be be working with.
saturate
Increase the saturation of a color in the HSL color space by an absolute amount.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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
.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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
.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%. -
method
: Optional, set torelative
for the adjustment to be relative to the current value.
Returns: color
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.
Parameters:
-
color
: A color object. -
amount
: A percentage 0-100%.
Returns: color
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 e.g. angles of 360 and 720 will produce the same result. Note that colors are passed through an RGB conversion, which doesn't retain hue value for greys (because hue has no meaning when there is no saturation), so make sure you apply functions in a way that preserves hue, for example don't do this:
@c: saturate(spin(#aaaaaa, 10), 10%);
Do this instead:
@c: spin(saturate(#aaaaaa, 10%), 10);
Colors are always returned as RGB values, so applying spin
to a grey value will do nothing.
Parameters:
-
color
: A color object. -
angle
: A number of degrees to rotate (+ or -).
Returns: color
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.
Parameters:
-
color1
: A color object. -
color2
: A color object. -
weight
: Optional, a percentage balance point between the two colors, defaults to 50%.
Returns: color
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)
Parameters:
-
color
: A color object. -
weight
: Optional, a percentage balance point between color and white, defaults to 50%.
Returns: color
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)
Parameters:
-
color
: A color object. -
weight
: Optional, a percentage balance point between color and black, defaults to 50%.
Returns: color
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%)
.
Because the saturation is not affected by hue, the resulting color mapping may be somewhat dull or muddy; luma
may provide a better result as it extracts perceptual rather than linear brightness, for example greyscale('#0000ff')
will return the same value as greyscale('#00ff00')
, though they appear quite different in brightness to the human eye.
Parameters: color
: A color object.
Returns: color
Example: greyscale(hsl(90, 90%, 50%))
Output: #808080 // hsl(90, 0%, 50%)
➜
Notice that the generated grey looks darker than the original green, even though its lightness value is the same.
Compare with using luma
(usage is different because luma
returns a single value, not a color):
@c: luma(hsl(90, 90%, 50%)); color: rgb(@c, @c, @c);
Output: #cacaca
➜
This time the grey's lightness looks about the same as the green, though its value is actually higher.
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. In accordance with WCAG 2.0, colors are compared using their gamma-corrected luma value, not their lightness.
The light and dark parameters can be supplied in either order - the function will calculate their luma values and assign light and dark automatically, which means you can't use this function to select the least contrasting color by reversing the order.
Parameters:
-
color
: A color object to compare against. -
dark
: optional - A designated dark color (defaults to black). -
light
: optional - A designated light color (defaults to white). -
threshold
: optional - A percentage 0-100% specifying where the transition from "dark" to "light" is (defaults to 43%, matching SASS). This is used to bias the contrast one way or another, for example to allow you to decide whether a 50% grey background should result in black or white text. You would generally set this lower for 'lighter' palettes, higher for 'darker' ones.
Returns: color
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, as in the last example:
Color Blending Functions
These operations are similar (though not necessarily identical) to the blend modes found in image editors like Photoshop, Fireworks, or GIMP, so you can use them to make your CSS colors match your images.
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.
Parameters:
-
color1
: A color object. -
color2
: A color object.
Returns: color
Examples:
multiply(#ff6600, #000000);
multiply(#ff6600, #333333);
multiply(#ff6600, #666666);
multiply(#ff6600, #999999);
multiply(#ff6600, #cccccc);
multiply(#ff6600, #ffffff);
multiply(#ff6600, #ff0000);
multiply(#ff6600, #00ff00);
multiply(#ff6600, #0000ff);
screen
Do the opposite of multiply
. The result is a brighter color.
Parameters:
-
color1
: A color object. -
color2
: A color object.
Returns: color
Example:
screen(#ff6600, #000000);
screen(#ff6600, #333333);
screen(#ff6600, #666666);
screen(#ff6600, #999999);
screen(#ff6600, #cccccc);
screen(#ff6600, #ffffff);
screen(#ff6600, #ff0000);
screen(#ff6600, #00ff00);
screen(#ff6600, #0000ff);
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.
Parameters:
-
color1
: A base color object. Also the determinant color to make the result lighter or darker. -
color2
: A color object to overlay.
Returns: color
Example:
overlay(#ff6600, #000000);
overlay(#ff6600, #333333);
overlay(#ff6600, #666666);
overlay(#ff6600, #999999);
overlay(#ff6600, #cccccc);
overlay(#ff6600, #ffffff);
overlay(#ff6600, #ff0000);
overlay(#ff6600, #00ff00);
overlay(#ff6600, #0000ff);
softlight
Similar to overlay
but avoids pure black resulting in pure black, and pure white resulting in pure white.
Parameters:
-
color1
: A color object to soft light another. -
color2
: A color object to be soft lighten.
Returns: color
Example:
softlight(#ff6600, #000000);
softlight(#ff6600, #333333);
softlight(#ff6600, #666666);
softlight(#ff6600, #999999);
softlight(#ff6600, #cccccc);
softlight(#ff6600, #ffffff);
softlight(#ff6600, #ff0000);
softlight(#ff6600, #00ff00);
softlight(#ff6600, #0000ff);
hardlight
The same as overlay
but with the color roles reversed.
Parameters:
-
color1
: A color object to overlay. -
color2
: A base color object. Also the determinant color to make the result lighter or darker.
Returns: color
Example:
hardlight(#ff6600, #000000);
hardlight(#ff6600, #333333);
hardlight(#ff6600, #666666);
hardlight(#ff6600, #999999);
hardlight(#ff6600, #cccccc);
hardlight(#ff6600, #ffffff);
hardlight(#ff6600, #ff0000);
hardlight(#ff6600, #00ff00);
hardlight(#ff6600, #0000ff);
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.
Parameters:
-
color1
: A color object to act as the minuend. -
color2
: A color object to act as the subtrahend.
Returns: color
Example:
difference(#ff6600, #000000);
difference(#ff6600, #333333);
difference(#ff6600, #666666);
difference(#ff6600, #999999);
difference(#ff6600, #cccccc);
difference(#ff6600, #ffffff);
difference(#ff6600, #ff0000);
difference(#ff6600, #00ff00);
difference(#ff6600, #0000ff);
exclusion
A similar effect to difference
with lower contrast.
Parameters:
-
color1
: A color object to act as the minuend. -
color2
: A color object to act as the subtrahend.
Returns: color
Example:
exclusion(#ff6600, #000000);
exclusion(#ff6600, #333333);
exclusion(#ff6600, #666666);
exclusion(#ff6600, #999999);
exclusion(#ff6600, #cccccc);
exclusion(#ff6600, #ffffff);
exclusion(#ff6600, #ff0000);
exclusion(#ff6600, #00ff00);
exclusion(#ff6600, #0000ff);
average
Compute the average of two colors on a per-channel (RGB) basis.
Parameters:
-
color1
: A color object. -
color2
: A color object.
Returns: color
Example:
average(#ff6600, #000000);
average(#ff6600, #333333);
average(#ff6600, #666666);
average(#ff6600, #999999);
average(#ff6600, #cccccc);
average(#ff6600, #ffffff);
average(#ff6600, #ff0000);
average(#ff6600, #00ff00);
average(#ff6600, #0000ff);
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.
Parameters:
-
color1
: A color object to act as the minuend. -
color2
: A color object to act as the subtrahend.
Returns: color
Example:
negation(#ff6600, #000000);
negation(#ff6600, #333333);
negation(#ff6600, #666666);
negation(#ff6600, #999999);
negation(#ff6600, #cccccc);
negation(#ff6600, #ffffff);
negation(#ff6600, #ff0000);
negation(#ff6600, #00ff00);
negation(#ff6600, #0000ff);
© 2009–2020 The Core Less Team
Licensed under the Creative Commons Attribution License 3.0.
http://lesscss.org/functions