Less (Leaner Style Sheets) Documentation

website·Indexed 43 days ago

https://lesscss.org

A backwards-compatible language extension for CSS. This documentation covers core features such as variables, mixins, and built-in logical, string, and list functions, as well as command-line usage via lessc, plugin integration, and compatible development tools.

Tokens
17K
Snippets
156
Records
173
Agent score
75%

What's inside Less

  1. Understand Less.js licensing terms

    Less.js is released under the Apache 2 License.

    Permissions:

    • Free download and use for personal, internal, or commercial purposes.
    • Inclusion in custom packages or distributions.

    Requirements:

    • Include a copy of the license in any redistribution.
    • Provide clear attribution to The Less Core Team.

    Restrictions:

    • Redistribution without proper attribution is forbidden.

    Not Required:

    • You are not required to include the source code of Less.js or your modifications in redistributions, nor are you required to submit changes back to the project.
  2. Escape strings in Less

    Escaping allows arbitrary strings to be used as property or variable values. Use ~"string" or ~'string'. As of Less 3.5, many cases no longer require quote-escaping and can be written as standard parentheses.
    // Traditional escaping
    @min768: ~"(min-width: 768px)";
    
    // Less 3.5+ simplified syntax
    @min768: (min-width: 768px);
    
    .element {
      @media @min768 {
        font-size: 1.2rem;
      }
    }
  3. Perform advanced selector manipulation with &

    The & operator can be used multiple times to refer to parent selectors repeatedly, or placed after a selector to prepend a class to the parent (changing the selector order).
    // Multiple & usage
    .link {
      & + & { color: red; } // .link + .link
      && { color: blue; }    // .link.link
    }
    
    // Changing selector order (Prepending)
    .header {
      .menu {
        .no-borderradius & { background-image: url('...'); }
        // Compiles to: .no-borderradius .header .menu
      }
    }
  4. Modify color opacity with fadein, fadeout, and fade

    Less provides three functions to manage opacity:

    • fadein(color, amount, [method]): Increases opacity (makes color more opaque).
    • fadeout(color, amount, [method]): Decreases opacity (makes color more transparent).
    • fade(color, amount): Sets the absolute opacity of a color regardless of its current state.
    fadein(hsla(90, 90%, 50%, 0.5), 10%);  // Output: rgba(128, 242, 13, 0.6)
    fadeout(hsla(90, 90%, 50%, 0.5), 10%); // Output: rgba(128, 242, 13, 0.4)
    fade(hsl(90, 90%, 50%), 10%);          // Output: rgba(128, 242, 13, 0.1)
  5. Merge property values using the merge feature

    The merge feature allows aggregating values from multiple properties into a single comma- or space-separated list. This is particularly useful for properties like background and transform. To prevent unintentional joins, an explicit + or +_ flag is required on each join-pending declaration.
    /* Comma-separated merge (using +) */
    .mixin() {
      box-shadow+: inset 0 0 10px #555;
    }
    .myclass {
      .mixin();
      box-shadow+: 0 0 20px black;
    }
    /* Output: box-shadow: inset 0 0 10px #555, 0 0 20px black; */
    
    /* Space-separated merge (using +_) */
    .mixin() {
      transform+_: scale(2);
    }
    .myclass {
      .mixin();
      transform+_: rotate(15deg);
    }
    /* Output: transform: scale(2) rotate(15deg); */
  6. Use nesting and parent selectors in Less

    Less supports nesting selectors to mimic HTML structure and reduce repetition. The & symbol is used as a parent selector to reference the current selector parent, which is particularly useful for pseudo-selectors.
    #header {
      color: black;
      .navigation {
        font-size: 12px;
      }
      .logo {
        width: 300px;
      }
    }
    
    .clearfix {
      display: block;
      zoom: 1;
    
      &:after {
        content: " ";
        display: block;
        font-size: 0;
        height: 0;
        clear: both;
        visibility: hidden;
      }
    }
  7. Use Maps for value storage in Less

    As of Less 3.5, mixins and rulesets can be used as maps to store and retrieve values using bracket notation [key].
    #colors() {
      primary: blue;
      secondary: green;
    }
    
    .button {
      color: #colors[primary];
      border: 1px solid #colors[secondary];
    }
  8. Use CSS properties as variables

    Introduced in v3.0.0, you can treat CSS properties as variables using the $prop syntax. Less will use the last property value found within the current or parent scope.
    .widget {
      color: #efefef;
      background-color: $color; // Uses the value of 'color' property
    }
  9. Create a Less.js plugin function

    To add a custom function to Less, use the functions.add method within the plugin's install function.

    • Plain Text Output: Returning a primitive (like a number or string) results in plain text output in the CSS.
    • Less Node Output: To allow the function result to be used in Less operations (e.g., multiplication), return a Less node, such as new tree.Dimension(value).
    • Null Output: To call a function without producing any CSS output (e.g., for state storage), return false.
    // Using module.exports for Node.js and Browser compatibility
    module.exports = {
        install: function(less, pluginManager, functions) {
            // Returns a value that can be used in Less operations
            functions.add('pi', function() {
                return new tree.Dimension(Math.PI);
            });
    
            // Returns false to produce no output in the final CSS
            functions.add('store', function(val) {
                console.log('Storing value:', val);
                return false;
            });
        }
    };
  10. Handle variable arguments in Less mixins

    Use the ... syntax to allow a mixin to accept a variable number of arguments. When placed after a variable name, it assigns the remaining arguments to that variable. The special variable @arguments is always available and contains all arguments passed to the mixin.
    .mixin(...) {        // matches 0-N arguments
    .mixin() {           // matches exactly 0 arguments
    .mixin(@a: 1) {      // matches 0-1 arguments
    .mixin(@a: 1, ...) { // matches 0-N arguments
    .mixin(@a, ...) {    // matches 1-N arguments
    
    .mixin(@a, @rest...) {
       // @rest is bound to arguments after @a
       // @arguments is bound to all arguments
    }
  11. Load plugins via Less.js in Node

    To use a plugin in a Node.js environment, require the plugin module and pass it to the less.render function within the plugins array option.
    var LessPlugin = require('less-plugin-myplugin');
    less.render(myCSS, { plugins: [LessPlugin] })
      .then(
        function(output) { },
        function(error) { }
      );
  12. Apply conditional logic with Mixin Guards

    Guards use the when keyword to execute a mixin only if a specific expression evaluates to true. This is the Less alternative to if/else statements.

    Comparison Operators: >, >=, =, =<, <. Truthiness: Only the keyword true is truthy; all other values are falsy.

    .mixin(@a) when (lightness(@a) >= 50%) {
      background-color: black;
    }
    .mixin(@a) when (lightness(@a) < 50%) {
      background-color: white;
    }
    .mixin(@a) {
      color: @a;
    }
    
    .class1 { .mixin(#ddd) } // Matches first and third
    .class2 { .mixin(#555) } // Matches second and third