### Plugin Install Function Example Source: https://lesscss.org/features An example of the 'install' function within a Less plugin file, demonstrating how to add a 'pi' function. ```javascript // my-plugin.js install: function(less, pluginManager, functions) { functions.add('pi', function() { return Math.PI; }); } // etc ``` -------------------------------- ### Registering a Simple Plugin Function Source: https://lesscss.org/features Define a plugin by registering an 'install' function that adds custom functions to Less. This example adds a 'pi' function. ```javascript registerPlugin({ install: function(less, pluginManager, functions) { functions.add('pi', function() { return Math.PI; }); } }) ``` -------------------------------- ### Install and Use Less.js with Node.js Source: https://lesscss.org/ Install Less globally using npm and compile Less files to CSS using the lessc command. ```bash npm install -g less ``` ```bash > lessc styles.less styles.css ``` -------------------------------- ### Install Less Globally Source: https://lesscss.org/usage Installs the `lessc` command-line compiler globally using npm. Use `@VERSION` to specify a version. ```bash npm install less -g ``` -------------------------------- ### Less @import Multiple Options Example Source: https://lesscss.org/features Demonstrates combining multiple import options, such as 'optional' and 'reference', separated by commas. ```less @import (optional, reference) "foo.less"; ``` -------------------------------- ### Less Mixins Example Source: https://lesscss.org/ Shows how to define a reusable set of CSS properties in a Less class and then include it in other selectors. ```less .bordered { border-top: dotted 1px black; border-bottom: solid 2px black; } #menu a { color: #111; .bordered(); } .post a { color: red; .bordered(); } ``` -------------------------------- ### Less Variables Example Source: https://lesscss.org/ Demonstrates the use of variables in Less, including basic assignments and calculations. ```less @width: 10px; @height: @width + 10px; #header { width: @width; height: @height; } ``` ```css #header { width: 10px; height: 20px; } ``` -------------------------------- ### Install Less Plugin via NPM Source: https://lesscss.org/usage Install a Less.js plugin using npm. Plugins are often registered with the 'less-plugin-' prefix for easier discovery. ```bash npm install less-plugin-myplugin ``` -------------------------------- ### Compile Less to CSS Source: https://lesscss.org/usage Example of compiling a specific Less file (`bootstrap.less`) to its corresponding CSS file (`bootstrap.css`) using the command line. ```bash lessc bootstrap.less bootstrap.css ``` -------------------------------- ### Install Less Globally Source: https://lesscss.org/usage Install the Less compiler globally using npm. This makes the `lessc` command available in your system's PATH. ```bash npm -g install less ``` -------------------------------- ### Less Escaping Output Example Source: https://lesscss.org/ The resulting CSS output from the escaping example using the tilde operator. ```css @media (min-width: 768px) { .element { font-size: 1.2rem; } } ``` -------------------------------- ### Less Comments Syntax Source: https://lesscss.org/ Provides examples of both block-style (/* ... */) and inline-style (// ...) comments in Less. ```less /* One heck of a block * style comment! */ @var: red; // Get in line! @var: white; ``` -------------------------------- ### Using the Null 'store' Function Source: https://lesscss.org/features Example of using the '@plugin' directive and the custom 'store' function to add a value to a collection without generating CSS. ```less @plugin "collections"; @var: 32; store(@var); ``` -------------------------------- ### Less Mixin with Parent Selector Example Source: https://lesscss.org/ Demonstrates creating a mixin for the clearfix hack using the '&' to refer to the parent selector. ```less .clearfix { display: block; zoom: 1; &:after { content: " "; display: block; font-size: 0; height: 0; clear: both; visibility: hidden; } } ``` -------------------------------- ### Less Color Functions Example Source: https://lesscss.org/ Demonstrates the usage of Less's built-in color functions, such as `percentage`, `saturate`, `lighten`, and `spin`, to manipulate color values and properties. ```less @base: #f04615; @width: 0.5; .class { width: percentage(@width); // returns `50%` color: saturate(@base, 5%); background-color: spin(lighten(@base, 25%), 8); } ``` -------------------------------- ### Less Nesting Example Source: https://lesscss.org/ Illustrates how to use nested selectors in Less to mimic HTML structure and reduce repetition. ```less #header { color: black; .navigation { font-size: 12px; } .logo { width: 300px; } } ``` -------------------------------- ### Install Less for Node Development Source: https://lesscss.org/usage Installs Less as a development dependency within a project, adding it to `devDependencies` in `package.json`. ```bash npm i less --save-dev ``` -------------------------------- ### Less.js Version Check Source: https://lesscss.org/usage Command-line flags to display the installed version of the Less compiler. ```bash lessc -v lessc --version ``` -------------------------------- ### Less @import Reference Example with Extend Source: https://lesscss.org/features Demonstrates using `@import (reference)` with the `:extend` pseudo-class to selectively pull styles, like specific components from a library. ```less .navbar:extend(.navbar all) {} ``` -------------------------------- ### Extend Example with Output Source: https://lesscss.org/features Demonstrates how `:extend` merges selectors. The extending selector (`nav ul`) is applied to the `.inline` class, and the declaration block is preserved. ```less nav ul { &:extend(.inline); background: blue; } .inline { color: red; } ``` -------------------------------- ### Plugin Function Definitions for Scope Example Source: https://lesscss.org/features Illustrates how two different plugins can define a function with the same name ('foo') without conflicts. ```javascript // lib1.js // ... functions.add('foo', function() { return "foo"; }); // ... // lib2.js // ... functions.add('foo', function() { return "bar"; }); // ... ``` -------------------------------- ### Attempting to Access Private Function Source: https://lesscss.org/features This example demonstrates that functions defined within a plugin's scope are not accessible globally, causing an error. ```less .el { @plugin "lib1"; } @value: foo(); ``` -------------------------------- ### % format Source: https://lesscss.org/functions Formats a string by replacing placeholders with provided arguments. Placeholders start with '%' followed by a letter indicating the type of replacement. ```APIDOC ## % format ### Description The function `%(string, arguments ...)` formats a string. The first argument is a string with placeholders. All placeholders start with a percentage symbol `%` followed by a 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 ```less 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 ```css 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"; ``` ``` -------------------------------- ### Less Scope Resolution Example Source: https://lesscss.org/ Illustrates Less's scope resolution, where variables and mixins are first looked for locally and then inherited from the parent scope, similar to CSS. ```less @var: red; #page { @var: white; #header { color: @var; // white } } ``` -------------------------------- ### Get Image Height - image-height() Source: https://lesscss.org/functions Retrieves the height of an image file. This function is environment-specific and currently only available in Node.js. ```less image-height("file.png"); ``` -------------------------------- ### Less Scope Resolution (Lazy Loading) Source: https://lesscss.org/ Shows an alternative way to define variables in Less, demonstrating that definitions do not have to precede their usage due to Less's lazy loading behavior, making the scope resolution identical to the previous example. ```less @var: red; #page { #header { color: @var; // white } @var: white; } ``` -------------------------------- ### Guarded Namespace Example (Unused Mixin) Source: https://lesscss.org/features Illustrates a scenario where nested guards prevent a mixin from ever being evaluated because one of the guards is guaranteed to be false. ```less #sp_1 when (default()) { #sp_2 when (default()) { .mixin() when not(default()) { /* */ } } } ``` -------------------------------- ### Generate CSS Grid Classes Recursively Source: https://lesscss.org/features A generic example of using a recursive loop to generate CSS grid classes. It defines column widths based on a given number. ```less .generate-columns(@n, @i: 1) when (@i =< @n) { .column-@{i} { width: (@i * 100% / @n); } .generate-columns(@n, (@i + 1)); } .generate-columns(4); ``` -------------------------------- ### Create greyscale using luma Source: https://lesscss.org/functions Demonstrates creating a greyscale color by using the `luma` function to extract perceptual brightness and then applying it to RGB channels. ```less @c: luma(hsl(90, 90%, 50%)); color: rgb(@c, @c, @c); ``` -------------------------------- ### Control URL Rewriting in Less Source: https://lesscss.org/usage Manage how URLs in imported Less files are rewritten to be relative to the base Less file. Options include 'off' (default), 'all' (rewrite all URLs), and 'local' (rewrite only relative URLs starting with '.'). ```bash lessc -ru=off ``` ```bash lessc --rewrite-urls=off ``` ```javascript { rewriteUrls: 'off' } ``` ```bash lessc -ru=all ``` ```bash lessc --rewrite-urls=all ``` ```javascript { rewriteUrls: 'all' } ``` ```bash lessc -ru=local ``` ```bash lessc --rewrite-urls=local ``` ```javascript { rewriteUrls: 'local' } ``` -------------------------------- ### Run Wro4j Runner CLI for Less CSS Source: https://lesscss.org/tools Use this command to preprocess Less CSS files with the Wro4j Runner CLI. Ensure the wro4j-runner.jar file is downloaded. ```bash java -jar wro4j-runner-1.5.0-jar-with-dependencies.jar --preProcessors lessCss ``` -------------------------------- ### Get Pi Value Source: https://lesscss.org/functions Returns the mathematical constant π (pi). ```less pi() ``` -------------------------------- ### Using the 'retrieve' Function Source: https://lesscss.org/features Demonstrates using the '@plugin' directive and the custom 'retrieve' function to output the stored values in a CSS property. ```less .get-my-values { @plugin "collections"; values: retrieve(); } ``` -------------------------------- ### Less.js Help Option Source: https://lesscss.org/usage Command-line flags to display a help message with available options for the Less compiler. ```bash lessc --help lessc -h ``` -------------------------------- ### Get the unit of a number Source: https://lesscss.org/functions The `get-unit` function returns the unit of a number. If the number has no unit, it returns an empty string. ```less get-unit(5px) ``` ```less get-unit(5) ``` -------------------------------- ### image-height Source: https://lesscss.org/functions Gets the image height from a file. This function needs to be implemented by each environment and is currently only available in the node environment. ```APIDOC ## image-height ### Description Gets the image height from a file. ### Parameters * `string`: the file to get the dimensions for. ### Returns * `dimension`: the height of the image. ### Example ```less image-height("file.png"); ``` ### Output ```css 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 ``` -------------------------------- ### Pre-Loading Plugins Source: https://lesscss.org/usage Information on how to pre-load Less.js plugins, especially for pre-processors, via the command line or programmatically. ```APIDOC ## Node.js Command Line Plugin Loading ### Description Installs and uses a Less.js plugin from the command line. Less.js attempts to load modules prefixed with `less-plugin-` or the specified plugin name when an unknown option is encountered. ### Installation ```bash npm install less-plugin-myplugin ``` ### Usage ```bash lessc --myplugin lessc --plugin=myplugin ``` ### Passing Options ```bash lessc --myplugin="advanced" lessc --plugin=myplugin=advanced ``` ``` ```APIDOC ## Loading a Plugin via Less.js (Node.js) ### Description Loads a Less.js plugin programmatically in a Node.js environment by requiring the plugin and passing it in an array to the `plugins` option during rendering. ### Code Example ```javascript var less = require('less'); var LessPluginMyPlugin = require('less-plugin-myplugin'); less.render(myCSS, { plugins: [LessPluginMyPlugin] }) .then(function(output) { /* ... */ }) .catch(function(error) { /* ... */ }); ``` ``` -------------------------------- ### Applying Different Plugins with Same Function Name Source: https://lesscss.org/features Shows how to use the '@plugin' directive to select which version of a function ('foo') to use in different CSS rules. ```less .el-1 { @plugin "lib1"; value: foo(); } .el-2 { @plugin "lib2"; value: foo(); } ``` -------------------------------- ### Mixins as Maps with Namespacing in Less Source: https://lesscss.org/features Illustrates using mixins with namespacing to create map-like structures. This allows for overloading and more versatile map implementations compared to simple rulesets. ```less #library() { .colors() { primary: green; secondary: blue; } } #library() { .colors() { primary: grey; } } .button { color: #library.colors[primary]; border-color: #library.colors[secondary]; } ``` ```less .button { color: grey; border-color: blue; } ``` -------------------------------- ### Render Less with Source Map Options (Promise) Source: https://lesscss.org/usage Render Less input and enable source map generation using the `sourceMap` option. The output object will contain the generated sourcemap. ```javascript less.render(lessInput, {sourceMap: {}}) .then(function(output) { // output.css = string of css // output.map = string of sourcemap } ``` -------------------------------- ### Convert Number to Percentage in Less Source: https://lesscss.org/functions The `percentage` function converts a floating-point number into a percentage string. For example, 0.5 becomes 50%. ```less percentage(0.5); ``` -------------------------------- ### Get List Length in Less Source: https://lesscss.org/functions Use the `length` function to determine the number of elements in a Less list. The list can be comma or space-separated. ```less length(1px solid #0080ff); ``` ```less @list: "banana", "tomato", "potato", "peach"; n: length(@list); ``` -------------------------------- ### Conditional styling with CSS Guards (Simple) Source: https://lesscss.org/features Demonstrates applying guards directly to selectors for conditional styling, a syntactic sugar for mixin guards. ```less button when (@my-option = true) { color: white; } ``` -------------------------------- ### Using Custom Function in Operations Source: https://lesscss.org/features Example of using the 'pi' function, which now returns a Less node, in a mathematical operation within a Less stylesheet. ```less @plugin "my-plugin"; .show-me-pi { value: pi() * 2; } ``` -------------------------------- ### Get image width Source: https://lesscss.org/functions The `image-width` function retrieves the width of an image file. Similar to `image-size`, this function is environment-specific and primarily available in Node.js. ```less image-width("file.png"); ``` -------------------------------- ### Get image dimensions Source: https://lesscss.org/functions The `image-size` function retrieves the width and height of an image file. Note: This function is environment-specific and currently only available in Node.js. ```less image-size("file.png"); ``` -------------------------------- ### Extend Syntax Variations Source: https://lesscss.org/features Shows different ways to use the `:extend` syntax, including attaching it directly to a selector or placing it within a ruleset body using `&:extend(selector)`. ```less .a:extend(.b) {} // the above block does the same thing as the below block .a { &:extend(.b); } ``` ```less .c:extend(.d all) { // extends all instances of ".d" e.g. ".x.d" or ".d.x" } .c:extend(.d) { // extends only instances where the selector will be output as just ".d" } ``` ```less .e:extend(.f) {} .e:extend(.g) {} // the above and the below do the same thing .e:extend(.f, .g) {} ``` -------------------------------- ### Using Parametric Mixins Source: https://lesscss.org/features Mix in parametric mixins by providing values for their arguments, allowing for reusable and customizable style blocks. ```less #header { .border-radius(4px); } .button { .border-radius(6px); } ``` -------------------------------- ### Recursive Mixin for Loops Source: https://lesscss.org/features Use recursive mixins with guards to create iterative CSS structures. This example generates nested width properties for each iteration. ```less .loop(@counter) when (@counter > 0) { .loop((@counter - 1)); // next iteration width: (10px * @counter); // code for each iteration } div { .loop(5); // launch the loop } ``` -------------------------------- ### Extending Nested Selectors Source: https://lesscss.org/features Demonstrates how `:extend` can target nested selectors. The example shows extending a nested ruleset (`tr`) within a parent (`.bucket`). ```less .bucket { tr { // nested ruleset with target selector color: blue; } } .some-class:extend(.bucket tr) {} // nested ruleset is recognized ``` -------------------------------- ### Run Less Compiler from Command Line Source: https://lesscss.org/usage Compile a Less file using the Less compiler executable. The output is sent to standard output. ```bash node bin/lessc path/to/file.less ``` -------------------------------- ### Less CSS Extend: Nth Expression Matching Source: https://lesscss.org/features The form of nth expressions must match exactly for extend to work. For example, '1n+3' and 'n+3' are considered different. ```less :nth-child(1n+3) { color: blue; } .child:extend(:nth-child(n+3)) {} ``` ```less :nth-child(1n+3) { color: blue; } ``` -------------------------------- ### Less.js Command Line Usage Source: https://lesscss.org/usage Basic syntax for using the `lessc` command-line tool to compile Less files to CSS. ```bash lessc [option option=parameter ...] [destination] ``` -------------------------------- ### Import as CSS with @import (css) Source: https://lesscss.org/features Use `@import (css)` to include files as regular CSS, leaving the import statement as is in the output. This is useful for importing pre-compiled CSS files. ```less @import (css) "foo.less"; ``` -------------------------------- ### Allow Insecure HTTPS Imports Source: https://lesscss.org/usage Allows Less to import files from HTTPS hosts that have insecure certificates. ```bash lessc --insecure ``` ```javascript { insecure: true } ``` -------------------------------- ### Mixin Call Syntax (Deprecated) Source: https://lesscss.org/features Demonstrates mixin call syntax, including deprecated forms. Optional parentheses are deprecated and will be required in a future release. ```less .a(); .a; // currently works, but deprecated; don't use .a (); // white-space before parentheses is also deprecated ``` -------------------------------- ### Detached Ruleset Scope: Caller Visibility Source: https://lesscss.org/features A detached ruleset can access variables and mixins from the caller's scope. The example shows how a detached ruleset references a caller-defined variable and mixin. ```less @detached-ruleset: { caller-variable: @caller-variable; // variable is undefined here .caller-mixin(); // mixin is undefined here }; selector { // use detached ruleset @detached-ruleset(); // define variable and mixin needed inside the detached ruleset @caller-variable: value; .caller-mixin() { variable: declaration; } } ``` ```css selector { caller-variable: value; variable: declaration; } ``` -------------------------------- ### Lazy Variable Evaluation in Less Source: https://lesscss.org/features Variables can be used before they are declared. The final value is determined by searching scopes upwards. This example shows a variable referencing another variable which is defined later. ```less .lazy-eval { width: @var; } @var: @a; @a: 9%; ``` ```less .lazy-eval { width: @var; @a: 9%; } @var: @a; @a: 100%; ``` ```css .lazy-eval { width: 9%; } ``` -------------------------------- ### Load Less Plugin via Command Line Source: https://lesscss.org/usage Load a Less.js plugin using the command line. Less.js attempts to load modules prefixed with 'less-plugin-' or the module name itself when an unknown option is encountered. ```bash lessc --myplugin ``` ```bash lessc --plugin=myplugin ``` -------------------------------- ### Detached Ruleset Scope: Referencing Does Not Modify Source: https://lesscss.org/features Referencing a detached ruleset does not grant it access to new scopes. The example demonstrates an error when a detached ruleset tries to access a variable not in its definition scope. ```less @detached-1: { scope-detached: @one @two; }; .one { @one: visible; .two { @detached-2: @detached-1; // copying/renaming ruleset @two: visible; // ruleset can not see this variable } } .use-place { .one > .two(); @detached-2(); } ``` -------------------------------- ### Advanced Mixin Alternative with Extend Source: https://lesscss.org/features Demonstrates using :extend as an alternative to mixins for applying the same styles to different HTML blocks. This is useful when mixins cannot be used with complex selectors. ```less li.list > a { // list styles } button.list-style { &:extend(li.list > a); } ``` -------------------------------- ### Less Namespace for Mixins and Variables Source: https://lesscss.org/ Shows how to create and use namespaces in Less to group mixins and variables for better organization and encapsulation. Appending `()` to the namespace prevents it from appearing in the CSS output. ```less #bundle() { .button { display: block; border: 1px solid black; background-color: grey; &:hover { background-color: white; } } .tab { ... } .citation { ... } } #header a { color: orange; #bundle.button(); // can also be written as #bundle > .button } ``` -------------------------------- ### Example of Strict Units Error Source: https://lesscss.org/usage This Less code snippet demonstrates a calculation that would trigger a strict units error if the --strict-units option is enabled, as it involves multiplying two length units. ```less .class { property: 1px * 2px; } ``` -------------------------------- ### Generate Range of Values in Less Source: https://lesscss.org/functions The `range` function creates a list of numbers within a specified range. It can take a start, end, and step value. The unit of the output values matches the unit of the `end` parameter. ```less value: range(4); ``` ```less value: range(10px, 30px, 10); ``` -------------------------------- ### Less Variable Interpolation in URLs Source: https://lesscss.org/features Demonstrates using Less variables within URL paths for dynamic background image referencing. This helps in managing asset paths efficiently. ```less // Variables @images: "../img"; // Usage body { color: #444; background: url("@{images}/white-sand.png"); } ``` -------------------------------- ### Configure Include Paths for Less Imports Source: https://lesscss.org/usage Specify directories where Less should search for files referenced in @import rules if they are not found at the exact specified location. Useful for referencing library files relatively. ```bash lessc --include-path=PATH1;PATH2 ``` ```javascript { paths: ['PATH1', 'PATH2'] } ``` -------------------------------- ### Configuring Less.js Options Source: https://lesscss.org/usage Less.js options can be configured by setting a global `less` object before loading the `less.js` script. This allows customization of environment, logging, asynchronous loading, and more. ```APIDOC ## Options Set options in a global `less` object **before** loading the less.js script: ```html ``` ``` -------------------------------- ### Registering a Plugin with module.exports Source: https://lesscss.org/features Alternatively, define a plugin using 'module.exports', which is shimmed to work in both browser and Node.js environments. ```javascript module.exports = { install: function(less, pluginManager, functions) { functions.add('pi', function() { return Math.PI; }); } }; ``` -------------------------------- ### Configure Less.js Options Before Loading Source: https://lesscss.org/usage Set various Less.js options globally in a 'less' object before the less.js script is loaded. This allows configuration of environment, logging, asynchronous loading, and more. ```html ``` -------------------------------- ### Nested At-Rules and Bubbling in Less Source: https://lesscss.org/ Shows how at-rules like @media can be nested within selectors, and how they bubble up to form combined rules. ```less .component { width: 300px; @media (min-width: 768px) { width: 600px; @media (min-resolution: 192dpi) { background-image: url(/img/retina2x.png); } } @media (min-width: 1280px) { width: 800px; } } ``` ```css .component { width: 300px; } @media (min-width: 768px) { .component { width: 600px; } } @media (min-width: 768px) and (min-resolution: 192dpi) { .component { background-image: url(/img/retina2x.png); } } @media (min-width: 1280px) { .component { width: 800px; } } ``` -------------------------------- ### Compile Less.js using dotless Source: https://lesscss.org/tools Compile Less.js files to CSS using the dotless.Compiler.exe tool. Accepts switches and input/output file arguments. ```bash dotless.Compiler.exe [-switches] [outputfile] ``` -------------------------------- ### Using Rulesets as Maps in Less Source: https://lesscss.org/features Shows how to use detached rulesets as maps to store and access values by key. This feature, available since Less v3.5.0, enhances organization and retrieval of configuration data. ```less @sizes: { mobile: 320px; tablet: 768px; desktop: 1024px; } .navbar { display: block; @media (min-width: @sizes[tablet]) { display: inline-block; } } ``` ```less .navbar { display: block; } @media (min-width: 768px) { .navbar { display: inline-block; } } ``` -------------------------------- ### Less Arithmetic on Colors Source: https://lesscss.org/ Shows how arithmetic operations can be performed on color values in Less. Division by a number results in a darker shade, and addition combines colors. ```less @color: (#224488 / 2); // result is #112244 background-color: #112244 + #111; // result is #223355 ``` -------------------------------- ### Less Mixins as Maps Source: https://lesscss.org/ Demonstrates using Less mixins and rulesets as maps of values, allowing access to specific properties using map-like syntax. This feature was introduced in Less 3.5. ```less #colors() { primary: blue; secondary: green; } .button { color: #colors[primary]; border: 1px solid #colors[secondary]; } ``` -------------------------------- ### Compile Less.js using lessc command Source: https://lesscss.org/tools Directly use the lessc command-line tool to compile Less.js input files to CSS. Supports an optional compress flag. ```bash lessc input.less [output.css] [-compress] ``` -------------------------------- ### Allow Multiple Imports with @import (multiple) Source: https://lesscss.org/features Use `@import (multiple)` to permit importing files with the same name multiple times. This contrasts with the default `once` behavior and is useful when you need to include the same styles in different contexts. ```less // file: foo.less .a { color: green; } // file: main.less @import (multiple) "foo.less"; @import (multiple) "foo.less"; ``` -------------------------------- ### Namespacing for Library Organization Source: https://lesscss.org/features Organize mixins within a namespace, like `#my-library`, to prevent conflicts and structure code. Use the namespaced mixin with dot notation. ```less #my-library { .my-mixin() { color: black; } } // which can be used like this .class { #my-library.my-mixin(); } ``` -------------------------------- ### softlight Source: https://lesscss.org/functions Similar to 'overlay' but avoids pure black and pure white results, offering a softer blending effect. ```APIDOC ## softlight ### Description Similar to 'overlay' but avoids pure black and pure white results, offering a softer blending effect. ### Parameters * `color1`: A color object to _soft light_ another. * `color2`: A color object to be _soft lighten_. ### Returns `color` ### Example ```less 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); ``` ``` -------------------------------- ### Less Arithmetic Operations with Units Source: https://lesscss.org/ Demonstrates how Less handles arithmetic operations with units, including conversions and incompatible unit handling. Variables can also be used in these operations. ```less // numbers are converted into the same units @conversion-1: 5cm + 10mm; // result is 6cm @conversion-2: 2 - 3cm - 5mm; // result is -1.5cm // conversion is impossible @incompatible-units: 2 + 5px - 3cm; // result is 4px // example with variables @base: 5%; @filler: @base * 2; // result is 10% @other: @base + @filler; // result is 15% ``` -------------------------------- ### Compile Less.js using Windows Script Host Source: https://lesscss.org/tools Compile Less.js input files to CSS using the Windows Script Host. Supports an optional compress flag. ```batch cscript //nologo lessc.wsf input.less [output.css] [-compress] ``` -------------------------------- ### Create an opaque color object Source: https://lesscss.org/functions The `rgb` function creates an opaque color from decimal red, green, and blue values. Standard HTML/CSS color formats are also accepted. ```less rgb(90, 129, 32) ``` -------------------------------- ### Classic Use Case for Extend: Avoiding Base Class Duplication Source: https://lesscss.org/features Shows how :extend can be used to create subtypes of a base class without duplicating styles in HTML. This simplifies HTML structure by applying styles through Less. ```html Bear ``` ```less .animal { background-color: black; color: white; } .bear { &:extend(.animal); background-color: brown; } ``` -------------------------------- ### Import Less and CSS Files Source: https://lesscss.org/ Use the `@import` directive to include other Less or CSS files. The `.less` extension is optional. ```less @import "library"; // library.less ``` ```less @import "typo.css"; ``` -------------------------------- ### Convert Units - convert() Source: https://lesscss.org/functions Converts a numerical value from one unit to another if the units are compatible. Incompatible units result in the original value being returned. ```less convert(9s, "ms") convert(14cm, mm) convert(8, mm) // incompatible unit types ``` -------------------------------- ### Multiple Extends in a Ruleset Source: https://lesscss.org/features Illustrates how to apply multiple `:extend` clauses within a single ruleset, affecting multiple selectors simultaneously. ```less .big-division, .big-bag:extend(.bag), .big-bucket:extend(.bucket) { // body } ``` -------------------------------- ### Enable Less.js Watch Mode Source: https://lesscss.org/usage To enable watch mode, set the 'env' option to 'development' before including less.js, and then call less.watch(). Alternatively, append '#!watch' to the URL. ```html ``` -------------------------------- ### Variable Variables in Map Lookups (Less) Source: https://lesscss.org/features Explains and demonstrates the `@@variable` syntax for dynamically specifying the key name in map lookups, allowing for variable-driven data retrieval. ```less .foods() { @dessert: ice cream; } @key-to-lookup: dessert; .lunch { treat: .foods[@@key-to-lookup]; } ``` ```less .lunch { treat: ice cream; } ``` -------------------------------- ### Pass Options to Less Plugin via Command Line Source: https://lesscss.org/usage Pass options to a Less.js plugin directly from the command line. Options can be specified using equals signs or colons. ```bash lessc --myplugin="advanced" ``` ```bash lessc --plugin=myplugin=advanced ``` -------------------------------- ### Using a Custom Plugin Function in Stylesheet Source: https://lesscss.org/features Demonstrates how to use the custom 'pi' function defined in a Less plugin within a Less stylesheet. ```less @plugin "my-plugin"; .show-me-pi { value: pi(); } ``` -------------------------------- ### Emulate For Loop in Less Source: https://lesscss.org/functions A `for` loop can be emulated in Less by combining the `range` and `each` functions. This allows for generating dynamic rulesets based on a numerical sequence. ```less each(range(4), { .col-@{value} { height: (@value * 50px); } }); ``` -------------------------------- ### Programmatic Usage (Node.js) Source: https://lesscss.org/usage Details on how to use the `less.render` function in Node.js to compile Less code, with support for callbacks and promises. ```APIDOC ## `less.render` Function ### Description The primary function for compiling Less code programmatically in Node.js. It accepts Less input and an optional options object, returning a Promise or accepting a callback. ### Usage with Promises ```javascript less.render(lessInput, options) .then(function(output) { // output.css: Compiled CSS string // output.map: Sourcemap string (if enabled) // output.imports: Array of imported filenames }) .catch(function(error) { // Handle compilation errors }); ``` ### Usage with Callback ```javascript less.render(lessInput, options, function(error, output) { if (error) { // Handle compilation errors } else { // output.css: Compiled CSS string // output.map: Sourcemap string (if enabled) // output.imports: Array of imported filenames } }); ``` ### Rendering Files To render a file, read its content into a string and provide the filename in the options object. Less.js will automatically handle imports. ### Options - `sourceMap`: An object to configure source map generation. Available sub-options include `sourceMapURL`, `sourceMapBasepath`, `sourceMapRootpath`, `outputSourceFiles`, and `sourceMapFileInline`. Note: `sourceMap` is not available for the browser compiler. ### Examples with Source Maps **No Source Map:** ```javascript less.render(lessInput) .then(function(output) { // output.map will be undefined }); ``` **With Source Map:** ```javascript less.render(lessInput, { sourceMap: {} }) .then(function(output) { // output.map will contain the sourcemap }); ``` **Inline Source Map:** ```javascript less.render(lessInput, { sourceMap: { sourceMapFileInline: true } }) .then(function(output) { // output.css will contain the inline sourcemap // output.map will be undefined }); ``` ``` -------------------------------- ### Using Properties as Variables in Less Source: https://lesscss.org/features Properties can be referenced as variables using the `$prop` syntax. This can simplify code by reusing existing property values. ```less .widget { color: #efefef; background-color: $color; } ``` ```css .widget { color: #efefef; background-color: #efefef; } ``` -------------------------------- ### Detached Ruleset with Media Query Bubbling Source: https://lesscss.org/features Demonstrates media query bubbling within a detached ruleset. When the detached ruleset is called within a media query, the media query context is preserved and combined. ```less @my-ruleset: { .my-selector { @media tv { background-color: black; } } }; @media (orientation:portrait) { @my-ruleset(); } ``` ```css @media (orientation: portrait) and tv { .my-selector { background-color: black; } } ``` -------------------------------- ### Render Less Input with Promise API Source: https://lesscss.org/usage Use the `less.render` function with the promise-based API to compile Less input. The promise resolves with an output object containing CSS, map, and imports. ```javascript less.render(lessInput) .then(function(output) { // output.css = string of css // output.map = undefined } ``` -------------------------------- ### default Source: https://lesscss.org/functions Available only inside guard conditions and returns `true` only if no other mixin matches, `false` otherwise. ```APIDOC ## default ### Description Available only inside guard conditions and returns `true` only if no other mixin matches, `false` otherwise. 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: 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: However Less will throw a error if it detects a _potential_ conflict between multiple mixin definitions using `default()`: Advanced multiple `default()` usage: 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 ```less .mixin(1) {x: 11} .mixin(2) {y: 22} .mixin(@x) when (default()) {z: @x} div { .mixin(3); } div.special { .mixin(1); } ``` ### Output ```css div { z: 3; } div.special { x: 11; } ``` ### Example ```less .mixin(@value) when (ispixel(@value)) {width: @value} .mixin(@value) when not(default()) {padding: (@value / 5)} div-1 { .mixin(100px); } div-2 { /* ... */ .mixin(100%); } ``` ### Result ```css div-1 { width: 100px; padding: 20px; } div-2 { /* ... */ } ``` ### Example ```less div { .m(@x) when (default()), not(default()) {always: @x} .m(@x) when (default()) and not(default()) {never: @x} .m(1); // OK } ``` ### Example ```less div { .m(@x) when (default()) {} .m(@x) when not(default()) {} .m(1); // Error } ``` ### Example ```less .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 ```css .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; } ``` ### Example ```less div { foo: default(); bar: default(42); } ``` ### Result ```css div { foo: default(); bar: default(42); } ``` ``` -------------------------------- ### Duplication Detection with Extend Source: https://lesscss.org/features Demonstrates Less.js's current lack of duplication detection for :extend. Multiple selectors in an extend can lead to redundant output if not managed carefully. ```less .alert-info, .widget { /* declarations */ } .alert:extend(.alert-info, .widget) {} ``` ```less .alert-info, .widget, .alert, .alert { /* declarations */ } ``` -------------------------------- ### Render Less Input with Callback API Source: https://lesscss.org/usage Use the `less.render` function with a callback to compile Less input. The callback receives an error or an output object containing CSS, map, and imports. ```javascript less.render(css, options, function(error, output) {}) ``` -------------------------------- ### Less.js Browser Options Source: https://lesscss.org/usage Details various options available for Less.js when used in the browser, including `async`, `env`, `errorReporting`, `fileAsync`, `functions`, `logLevel`, `poll`, `relativeUrls`, and `useFileCache`. ```APIDOC ## Options specific to Less.js in the browser _For all other options, see Less Options._ #### async Type: `Boolean` Default: `false` Whether to request the import files with the async option or not. See fileAsync. #### env Type: `String` Default: depends on page URL Environment to run may be either `development` or `production`. In production, your css is cached in local storage and information messages are not output to the console. If the document's URL starts with `file://` or is on your local machine or has a non standard port, it will automatically be set to `development`. e.g. ```javascript less = { env: 'production' }; ``` #### errorReporting Type: `String` Options: `html`|`console`|`function` Default: `html` Set the method of error reporting when compilation fails. #### fileAsync Type: `Boolean` Default: `false` Whether to request the import asynchronously when in a page with a file protocol. #### functions (Deprecated - use @plugin) Type: `object` User functions, keyed by name. ```javascript less = { functions: { myfunc: function() { return less.Dimension(1); } } }; ``` and it can be used like a native Less function e.g. ```less .my-class { border-width: unit(myfunc(), px); } ``` #### logLevel Type: `Number` Default: 2 The amount of logging in the javascript console. Note: If you are in the `production` environment you will not get any logging. ``` 2 - Information and errors 1 - Errors 0 - Nothing ``` #### poll Type: `Integer` Default: `1000` The amount of time (in milliseconds) between polls while in watch mode. #### relativeUrls Type: `Boolean` Default: `false` Optionally adjust URLs to be relative. When false, URLs are already relative to the entry less file. #### useFileCache Type: `Boolean` Default: `true` (previously `false` in before v2) Whether to use the per session file cache. This caches less files so that you can call modifyVars and it will not retrieve all the less files again. If you use the watcher or call refresh with reload set to true, then the cache will be cleared before running. ```