LESS is a CSS pre-processor that enables customizable, manageable and reusable style sheet for website. LESS is a dynamic style sheet language that extends the capability of CSS. LESS is also cross browser friendly.
CSS Preprocessor is a scripting language that extends CSS and gets compiled into regular CSS syntax, so that it can be read by your web browser. It provides functionalities like variables, functions, mixins and operations that allow you to build dynamic CSS.
Let us now understand why do we use LESS.
LESS supports creating cleaner, cross-browser friendly CSS faster and easier.
LESS is designed in JavaScript and also created to be used in live, which compiles faster than other CSS pre-processors.
LESS keeps your code in modular way which is really important by making it readable and easily changeable.
Faster maintenance can be achieved by the use of LESS variables.
LESS was designed by Alexis Sellier in 2009. LESS is an open-source. The first version of LESS was written in Ruby; in the later versions, the use of Ruby was replaced by JavaScript.
Cleaner and more readable code can be written in an organized way.
We can define styles and it can be reused throughout the code.
LESS is based on JavaScript and is a super set of CSS.
LESS is an agile tool that sorts out the problem of code redundancy.
LESS easily generates CSS that works across the browsers.
LESS enables you to write better and well-organized code by using nesting.
Maintenance can be achieved faster by the use of variables.
LESS enables you to reuse the whole classes easily by referencing them in your rule sets.
LESS provides the use of operations that makes coding faster and saves time.
It takes time to learn if you are new to CSS preprocessing.
Due to the tight coupling between the modules, more efforts should be taken to reuse and/or test dependent modules.
LESS has less framework compared to older preprocessor like SASS, which consists of frameworks Compass, Gravity and Susy.
In this chapter, we will understand, in a step-by-step manner, how to install LESS.
Operating System − Cross-platform
Browser Support − IE (Internet Explorer 8+), Firefox, Google Chrome, Safari.
Let us now understand the installation of LESS.
Step 1 − We need NodeJs to run LESS examples. To download NodeJs, open the link https://nodejs.org/en/, you will see a screen as shown below −
Dowload the Latest Features version of the zip file.
Step 2 − Run the setup to install the Node.js on your system.
Step 3 − Next, Install LESS on the server via NPM (Node Package Manager). Run the following command in the command prompt.
npm install -g less
Step 4 − After successful installation of LESS, you will see the following lines on the command prompt −
`-- less@2.6.1 +-- errno@0.1.4 | `-- prr@0.0.0 +-- graceful-fs@4.1.3 +-- image-size@0.4.0 +-- mime@1.3.4 +-- mkdirp@0.5.1 | `-- minimist@0.0.8 +-- promise@7.1.1 | `-- asap@2.0.3 +-- request@2.69.0 | +-- aws-sign2@0.6.0 | +-- aws4@1.3.2 | | `-- lru-cache@4.0.0 | | +-- pseudomap@1.0.2 | | `-- yallist@2.0.0 | +-- bl@1.0.3 | | `-- readable-stream@2.0.6 | | +-- core-util-is@1.0.2 | | +-- inherits@2.0.1 | | +-- isarray@1.0.0 | | +-- process-nextick-args@1.0.6 | | +-- string_decoder@0.10.31 | | `-- util-deprecate@1.0.2 | +-- caseless@0.11.0 | +-- combined-stream@1.0.5 | | `-- delayed-stream@1.0.0 | +-- extend@3.0.0 | +-- forever-agent@0.6.1 | +-- form-data@1.0.0-rc4 | | `-- async@1.5.2 | +-- har-validator@2.0.6 | | +-- chalk@1.1.1 | | | +-- ansi-styles@2.2.0 | | | | `-- color-convert@1.0.0 | | | +-- escape-string-regexp@1.0.5 | | | +-- has-ansi@2.0.0 | | | | `-- ansi-regex@2.0.0 | | | +-- strip-ansi@3.0.1 | | | `-- supports-color@2.0.0 | | +-- commander@2.9.0 | | | `-- graceful-readlink@1.0.1 | | +-- is-my-json-valid@2.13.1 | | | +-- generate-function@2.0.0 | | | +-- generate-object-property@1.2.0 | | | | `-- is-property@1.0.2 | | | +-- jsonpointer@2.0.0 | | | `-- xtend@4.0.1 | | `-- pinkie-promise@2.0.0 | | `-- pinkie@2.0.4 | +-- hawk@3.1.3 | | +-- boom@2.10.1 | | +-- cryptiles@2.0.5 | | +-- hoek@2.16.3 | | `-- sntp@1.0.9 | +-- http-signature@1.1.1 | | +-- assert-plus@0.2.0 | | +-- jsprim@1.2.2 | | | +-- extsprintf@1.0.2 | | | +-- json-schema@0.2.2 | | | `-- verror@1.3.6 | | `-- sshpk@1.7.4 | | +-- asn1@0.2.3 | | +-- dashdash@1.13.0 | | | `-- assert-plus@1.0.0 | | +-- ecc-jsbn@0.1.1 | | +-- jodid25519@1.0.2 | | +-- jsbn@0.1.0 | | `-- tweetnacl@0.14.1 | +-- is-typedarray@1.0.0 | +-- isstream@0.1.2 | +-- json-stringify-safe@5.0.1 | +-- mime-types@2.1.10 | | `-- mime-db@1.22.0 | +-- node-uuid@1.4.7 | +-- oauth-sign@0.8.1 | +-- qs@6.0.2 | +-- stringstream@0.0.5 | +-- tough-cookie@2.2.2 | `-- tunnel-agent@0.4.2 `-- source-map@0.5.3
Following is a simple example of LESS.
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <h1>Welcome to Howcodex</h1> <h3>Hello!!!!!</h3> </body> </html>
Let us now create a file style.less which is quite similar to CSS, the only difference is that it will be saved with .less extension. Both the files, .html and .less should be created inside the folder nodejs.
@primarycolor: #FF7F50; @color:#800080; h1 { color: @primarycolor; } h3 { color: @color; }
Compile style.less file to style.css by using the following command −
lessc style.less style.css
When you run the above command, it will create the style.css file automatically. Whenever you change the LESS file, it's necessary to run the above command in the cmd and then the style.css file will get updated.
The style.css file will have the following code when you run the above command −
h1 { color: #FF7F50; } h3 { color: #800080; }
Let us now carry out the following steps to see how the above code works −
Save the above html code in the hello.htm file.
Open this HTML file in a browser, the following output will get displayed.
It is a group of CSS properties which allows using properties of one class into another class and includes the class name as its properties. In LESS, you can declare mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.
The following example demonstrates the use of nested rules in the LESS file −
<html> <head> <title>Nested Rules</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <div class = "container"> <h1>First Heading</h1> <p>LESS is a dynamic style sheet language that extends the capability of CSS.</p> <div class = "myclass"> <h1>Second Heading</h1> <p>LESS enables customizable, manageable and reusable style sheet for web site.</p> </div> </div> </body> </html>
Next, create the style.less file.
.container { h1 { font-size: 25px; color:#E45456; } p { font-size: 25px; color:#3C7949; } .myclass { h1 { font-size: 25px; color:#E45456; } p { font-size: 25px; color:#3C7949; } } }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.container h1 { font-size: 25px; color: #E45456; } .container p { font-size: 25px; color: #3C7949; } .container .myclass h1 { font-size: 25px; color: #E45456; } .container .myclass p { font-size: 25px; color: #3C7949; }
Follow these steps to see how the above code works −
Save the above html code in the nested_rules.html file.
Open this HTML file in a browser, the following output will get displayed.
You can nest the directives such as media and keyframe in the same manner, the way you nest the selectors. You can place the directive on top and its relative elements will not be changed inside its rule set. This is known as the bubbling process.
The following example demonstrates the use of the nested directives and bubbling in the LESS file −
<html> <head> <title>Nested Directives</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Nested Directives</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Next, create the file style.less.
.myclass { @media screen { color: blue; @media (min-width: 1024px) { color: green; } } @media mytext { color: black; } }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
@media screen { .myclass { color: blue; } } @media screen and (min-width: 1024px) { .myclass { color: green; } } @media mytext { .myclass { color: black; } }
Follow these steps to see how the above code works −
Save the above html code in the nested_directives_bubbling.html file.
Open this HTML file in a browser, the following output will get displayed.
LESS provides support for some arithmetical operations such as plus (+), minus (-), multiplication (*) and division (/) and they can operate on any number, color or variable. Operations save lot of time when you are using variables and you feel like working on simple mathematics.
The following example demonstrates the use of operations in the LESS file −
<html> <head> <title>Less Operations</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Operations</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Next, create the file style.less.
@fontSize: 10px; .myclass { font-size: @fontSize * 2; color:green; }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass { font-size: 20px; color: green; }
Follow these steps to see how the above code works −
Save the above html code in the operations.html file.
Open this HTML file in a browser, the following output will get displayed.
It builds selectors dynamically and uses property or variable value as arbitrary string.
The following example demonstrates the use of escaping in the LESS file −
<html> <head> <title>Less Escaping</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Escaping</h1> <p>LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Now create the style.less file.
p { color: ~"green"; }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command, it will create the style.css file automatically with the following code −
p { color: green; }
Anything written inside ~"some_text" will be displayed as some_text after compiling the LESS code to CSS code.
Let us now perform the following steps to see how the above code works −
Save the above html code in the escaping.html file.
Open this HTML file in a browser, the following output will get displayed.
LESS maps JavaScript code with manipulation of values and uses predefined functions to manipulate HTML elements aspects in the style sheet. It provides several functions to manipulate colors such as round function, floor function, ceil function, percentage function etc.
The following example demonstrates the use of functions in the LESS file −
<html> <head> <title>Less Functions</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Functions</h1> <p class = "mycolor">LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Now create the style.less file.
@color: #FF8000; @width:1.0; .mycolor { color: @color; width: percentage(@width); }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Now execute the above command; it will create the style.css file automatically with the following code −
.mycolor { color: #FF8000; width: 100%; }
Follow these steps to see how the above code works −
Save the above html code in the functions.html file.
Open this HTML file in a browser, displayed you will receive the following output.
Namespaces are used to group the mixins under a common name. Using namespaces, you can avoid conflict in name and encapsulate a group of mixins from outside.
The following example demonstrates the use of namespaces and accessors in the LESS file −
<html> <head> <title>Less Namespaces and Accessors</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Namespaces and Accessors</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Now create the style.less file.
.class1 { .class2 { .val(@param) { font-size: @param; color:green; } } } .myclass { .class1 > .class2 > .val(20px); }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass { font-size: 20px; color: green; }
Follow these steps to see how the above code works −
Save the above html code in the namespaces_accessors.html file.
Open this HTML file in a browser, the following output will get displayed.
Variable scope specifies the place of the available variable. The variables will be searched from the local scope and if they are not available, then compiler will search from the parent scope.
The following example demonstrates the use of namespaces and accessors in the LESS file −
<html> <head> <title>Less Scope</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Scope</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html>
Now create the style.less file.
@var: @a; @a: 15px; .myclass { font-size: @var; @a:20px; color: green; }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass { font-size: 20px; color: green; }
Follow these steps to see how the above code works −
Save the above html code in the scope.html file.
Open this HTML file in a browser, the following output will get displayed.
Comments make the code clear and understandable for the users. You can use both the block style and the inline comments in the code, but when you compile the LESS code, the single line comments will not appear in the CSS file.
The following example demonstrates the use of comments in the LESS file −
<html> <head> <title>Less Comments</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Comments</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> <p class = "myclass1">It allows reusing CSS code and writing LESS code with same semantics.</p> </body> </html>
Now create the style.less file.
/* It displays the green color! */ .myclass { color: green; } // It displays the blue color .myclass1 { color: red; }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Now execute the above command; it will create the style.css file automatically with the following code −
/* It displays the green color! */ .myclass { color: green; } .myclass1 { color: red; }
Follow these steps to see how the above code works −
Save the above html code in the comments.html file.
Open this HTML file in a browser, the following output will get displayed.
It is used to import the contents of the LESS or CSS files.
The following example demonstrates the use of importing in the LESS file −
<html> <head> <title>Less Importing</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Importing</h1> <p class = "myclass">LESS enables customizable, manageable and reusable style sheet for web site.</p> <p class = "myclass1">It allows reusing CSS code and writing LESS code with same semantics.</p> <p class = "myclass2">LESS supports creating cleaner, cross-browser friendly CSS faster and easier.</p> </body> </html>
Now create the myfile.less file.
.myclass { color: #FF8000; } .myclass1 { color: #5882FA; }
Now create the style.less file.
@import "http://www.howcodex.com/less/myfile.less"; .myclass2 { color: #FF0000; }
The myfile.less file which will be imported into style.less from the path https://www.howcodex.com/less/myfile.less
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myclass { color: #FF8000; } .myclass1 { color: #5882FA; } .myclass2 { color: #FF0000; }
Follow these steps to see how the above code works −
Save the above html code in the importing.html file.
Open this HTML file in a browser, the following output will get displayed.
In this chapter, we will discuss the Variables in LESS. LESS allows variables to be defined with an @ symbol. The Variable assignment is done with a colon(:).
The following table demonstrates the use of LESS variables in detail.
Sr.No. | Variables usage & Description |
---|---|
1 | Overview
Repetition of same value many times can be avoided by the use of variables. |
2 | Variable Interpolation
The variables can also be used in other places like selector names, property names, URLs and @import statements. |
3 | Variable Names
We can define variables with a variable name consisting of a value. |
4 | Lazy Loading
In lazy loading, variables can be used even when they are not. |
5 | Default Variables
Default variable has an ability to set a variable only when it is not already set. This feature is not required because variables can be easily overridden by defining them afterwards. |
Extend is a LESS pseudo class which extends other selector styles in one selector by using :extend selector.
The following example demonstrates the use of extend in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "style"> <h2>Welcome to Howcodex</h2> <p>Hello!!!!!</p> </div> </body> </html>
Next, create the style.less file.
h2 { &:extend(.style); font-style: italic; } .style { background: green; }
You can compile the extend.less file to extend.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
h2 { font-style: italic; } .style, h2 { background: blue; }
Follow these steps to see how the above code works −
Save the above html code in the extend_syntax.htm file.
Open this HTML file in a browser, the following output will get displayed.
Extend is placed into ruleset or attached to a selector. It is similar to a pseudo class containing one or more classes, which are separated by comma. Using the optional keyword all, each selector can be followed.
The following example demonstrates the use of extend syntax in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "style"> <h2>Welcome to Howcodex</h2> <div class = "container"> <p>Hello!!!!!</p> </div> </div> </body> </html>
Now create the style.less file.
.style:extend(.container, .img) { background: #BF70A5; } .container { font-style: italic; } .img { font-size: 30px; }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.style { background: #BF70A5; } .container, .style { font-style: italic; } .img, .style { font-size: 30px; }
Follow these steps to see how the above code works −
Save the above html code in the extend_syntax.htm file.
Open this HTML file in a browser, the following output will get displayed.
The following table lists all the types of extend syntax which you can use in LESS −
Sr.No. | Types & Description |
---|---|
1 | Extend Attached to Selector
Extend is connected to a selector which looks similar to a pseudo class with selector as parameter. |
2 | Extend Inside Ruleset
The &:extend(selector) syntax can be put inside the body of ruleset. |
3 | Extending Nested Selectors
Nested selectors are matched using the extend selector. |
4 | Exact Matching with Extend
By default, extend looks for the exact match between the selectors. |
5 | nth Expression
The form of nth expression is important in extend otherwise, it treats selector as different. |
6 | Extend "all"
When the keyword all is identified at last in the extend argument then LESS matches that selector as part of another selector. |
7 | Selector Interpolation with Extend
The extend can be connected to interpolated selector. |
8 | Scoping/Extend inside @media
Extend matches the selector only that is present inside the same media declaration. |
9 | Duplication Detection
It cannot detect the duplication of selectors. |
Following are the types of Use Cases for Extend
Sr.No. | Types & Description |
---|---|
1 | Classic Use Case
Classic use case is used to avoid adding the base class in LESS. |
2 | Reducing CSS Size
Extend is used to move the selector as far as the properties you want to use; this helps in reducing the css generated code. |
3 | Combining Styles/ A More Advanced Mixin
Using extend we can combine the same styles of a particular selectors into other selector. |
Mixins are similar to functions in programming languages. Mixins are a group of CSS properties that allow you to use properties of one class for another class and includes class name as its properties. In LESS, you can declare a mixin in the same way as CSS style using class or id selector. It can store multiple values and can be reused in the code whenever necessary.
The following table demonstrates the use of LESS mixins in detail.
Sr.No. | Mixins usage & Description |
---|---|
1 | Not Outputting the Mixin
Mixins can be made to disappear in the output by simply placing the parentheses after it. |
2 | Selectors in Mixins
The mixins can contain not just properties, but they can contain selectors too. |
3 | Namespaces
Namespaces are used to group the mixins under a common name. |
4 | Guarded Namespaces
When guard is applied to namespace, mixins defined by it are used only when the guard condition returns true. |
5 | The !important keyword
The !important keyword is used to override the particular property. |
The following example demonstrates the use of mixins in the LESS file −
<html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> <title>LESS Mixins</title> </head> <body> <h1>Welcome to Howcodex</h1> <p class = "p1">LESS is a CSS pre-processor that enables customizable, manageable and reusable style sheet for web site.</p> <p class = "p2">LESS is a dynamic style sheet language that extends the capability of CSS.</p> <p class = "p3">LESS is cross browser friendly.</p> </body> </html>
Next, create the style.less file.
.p1 { color:red; } .p2 { background : #64d9c0; .p1(); } .p3 { background : #LESS520; .p1; }
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.p1 { color: red; } .p2 { background: #64d9c0; color: red; } .p3 { background: #LESS520; color: red; }
Follow these steps to see how the above code works −
Save the above html code in the less_mixins.html file.
Open this HTML file in a browser, the following output will get displayed.
The parentheses are optional when calling mixins. In the above example, both statements .p1(); and .p1; do the same thing.
Parametric mixins use one or more parameters that extend functionality of LESS by taking arguments and its properties to customize the mixin output when mixed into another block.
For instance, consider a simple LESS code snippet −
.border(@width; @style; @color) { border: @width @style @color; } .myheader { .border(2px; dashed; green); }
Here we are using the parametric mixin as .border with three parameters - width, style and color. Using these parameters, you can customize the mixin output with the passed parameters value.
The following table describes the different types of parametric mixins along with description.
Sr.No. | Types & Description |
---|---|
1 | Mixins with Multiple Parameters
Parameters can be separated using commas or semicolon. |
2 | Named Parameters
Mixins provide parameter values instead of positions by using their names. |
3 | @arguments Variable
When a mixin is called, the @arguments include all the passed arguments. |
4 | Advanced Arguments and the @rest Variable
Mixin takes variable number of arguments by using ..... |
5 | Pattern-matching
Change the behavior of mixin by passing parameters to it. |
In this chapter, we will understand the importance of Mixins as Functions. Like functions, mixins can be nested, can accept parameters, and return values too.
The following table demonstrates the use of mixins as functions in details.
Sr.No. | Mixins usage & Description |
---|---|
1 | Mixin scope
Mixins consist of variables; these can be used in caller's scope and are visible. |
2 | Mixin and return values
Mixins are similar to functions and the variables that are defined in a mixin will behave as the return values. |
3 | Mixin inside another mixin
Whenever a mixin is defined inside another mixin, it can be used as return value too. |
Detached ruleset contains rulesets such as properties, nested rulesets, variables declaration, mixins, etc. It is stored in a variable and included in another structure; all the properties of the ruleset get copied to that structure.
The following example shows how to pass a ruleset to mixin in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "cont"> <h2>Welcome to Howcodex</h2> <p>The largest Tutorials Library on the web.</p> </div> </body> </html>
Next, create the style.less file.
@detached-ruleset: { .mixin() { font-family: "Comic Sans MS"; background-color: #AA86EE; } }; .cont { @detached-ruleset(); .mixin(); }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.cont { font-family: "Comic Sans MS"; background-color: #AA86EE; }
Follow these steps to see how the above code works −
Save the above html code in the passing_ruleset.htm file.
Open this HTML file in a browser, the following output will get displayed.
All variables and mixins in detached ruleset are available wherever the ruleset called or defined. Otherwise, both the caller and the definition scopes are available by default. The declaration scope takes the priority when both scopes contain same mixin or variable. Detached ruleset body is defined in the declaration scope. It does not change its scope after the detached ruleset is copied from one variable to another.
The following table lists all the types of scope −
Sr.No. | Types & Description |
---|---|
1 | Definition and Caller Scope Visibility
Variables and mixins are defined inside the detached ruleset. |
2 | Referencing Won't Modify Detached Ruleset Scope
Just giving the references, the ruleset does not access to any new scopes. |
3 | Unlocking Will Modify Detached Ruleset Scope
The detached ruleset can access to scope by being imported into it. |
The @import directive is used to import the files in the code. It spreads the LESS code over different files and allows to maintain the structure of code easily. You can put the @import statements anywhere in the code.
For instance, you can import the file by using @import keyword as @import "file_name.less".
You can use the @import statements depending on the different file extensions such as −
If you are using .css extension, then it will be considered as CSS and the @import statement remains as it is.
If it contains any other extension, then it will be considered as LESS and will be imported.
If there is no LESS extension, then it will appended and included as imported LESS file.
@import "style"; // imports the style.less @import "style.less"; // imports the style.less @import "style.php"; // imports the style.php as a less file @import "style.css"; // it will kept the statement as it is
The following example demonstrates the use of variable in the SCSS file −
<!doctype html> <head> <title>Import Directives</title> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <h2>Example of Import Directives</h2> <p class = "myline">Welcome to Howcodex...</p> </body> </html>
Next, create the import_dir.less file.
.myline { font-size: 20px; }
Now, create the style.less file.
@import "http://www.howcodex.com/less/import_dir.less"; .myline { color:#FF0000; }
The import_dir.less file will get imported into style.less file from the path https://www.howcodex.com/less/import_dir.less.
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.myline { font-size: 20px; } .myline { color: #FF0000; }
Follow these steps to see how the above code works −
Save the above html code in the import_directives.html file.
Open this HTML file in a browser, the following output will get displayed.
In this chapter, we will understand the importance of Import Options in LESS. LESS offers the @import statement that allows the style sheets to import both LESS and CSS style sheets.
The following tables lists the import directives that will be implemented in the import statements.
Sr.No. | Import options & Description |
---|---|
1 | reference
It uses a LESS file only as reference and will not output it. |
2 | inline
It enables you to copy your CSS into the output without being processed. |
3 | less
It will treat the imported file as the regular LESS file, despite whatever may be the file extension. |
4 | css
It will treat the imported file as the regular CSS file, despite whatever may be the file extension. |
5 | once
It will import the file only one time. |
6 | multiple
It will import the file multiple times. |
7 | optional
It continues compiling even though the file to import is not found. |
More than one keyword is allowed to use in the @import statement, however you have to use commas to seperate the keywords.
For instance −
@import (less, optional) "custom.css";
If you want to match simple values or number of arguments on expressions, then you can make use of guards. It is associated with mixin declaration and includes condition that is attached to a mixin. Each mixin will have one or more guards which are separated by comma; a guard must be enclosed within parentheses. LESS uses guarded mixins instead of if/else statements and performs calculations to specify matched mixin.
The following table describes the different types of mixins guards along with description.
Sr.No. | Types & Description |
---|---|
1 | Guard Comparison Operators
You can use the comparison operator (=) to compare numbers, strings, identifiers, etc. |
2 | Guard Logical Operators
You can use the and keyword to work around logical operators with guards. |
3 | Type Checking Functions
It contains the built-in functions to determine the value types for matching mixins. |
4 | Conditional Mixins
LESS uses the default function to match mixin with other mixing matches. |
The following example demonstrates the use of mixin guards in the LESS file −
<!doctype html> <head> <title>Mixin Guards</title> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <h2>Example of Mixin Guards</h2> <p class = "class1">Hello World...</p> <p class = "class2">Welcome to Howcodex...</p> </body> </html>
Now, create the style.less file.
.mixin (@a) when (lightness(@a) >= 50%) { font-size: 14px; } .mixin (@a) when (lightness(@a) < 50%) { font-size: 16px; } .mixin (@a) { color: @a; } .class1 { .mixin(#FF0000) } .class2 { .mixin(#555) }
You can compile the style.less to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.class1 { font-size: 14px; color: #FF0000; } .class2 { font-size: 16px; color: #555; }
Follow these steps to see how the above code works −
Save the above html code in the mixin-guard.html file.
Open this HTML file in a browser, the following output will get displayed.
Guards are used to match simple values or a number of arguments on expressions. It is applied to the CSS selectors. It is syntax for declaring mixin and calling it immediately. To successfully bring out the if type statement; join this with feature &, which allows you to group multiple guards.
The following example demonstrates the use of css guard in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "cont"> <h2>Welcome to Howcodex</h2> </div> <div class = "style"> <h3>The largest Tutorials Library on the web.</h3> </div> </body> </html>
Next, create the style.less file.
@usedScope: global; .mixin() { @usedScope: mixin; .cont when (@usedScope = global) { background-color: red; color: black; } .style when (@usedScope = mixin) { background-color: blue; color: white; } @usedScope: mixin; } .mixin();
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
.style { background-color: blue; color: white; }
Follow these steps to see how the above code works −
Save the above html code in the css_guard.htm file.
Open this HTML file in a browser, the following output will get displayed.
In this chapter, we will understand how Loops work in LESS. Loops statement allows us to execute a statement or group of statements multiple times. Various iterative/loop structures can be created when recursive mixin combine with Guard Expressions and Pattern Matching.
The following example demonstrates the use of loops in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> </head> <body> <div class = "cont"> <h2>Welcome to Howcodex</h2> <p>The largest Tutorials Library on the web. </p> </div> </body> </html>
Next, create the style.less file.
.cont(@count) when (@count > 0) { .cont((@count - 1)); width: (25px * @count); } div { .cont(7); }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
div { width: 25px; width: 50px; width: 75px; width: 100px; width: 125px; width: 150px; width: 175px; }
Follow these steps to see how the above code works −
Save the above html code in the loop_example.htm file.
Open this HTML file in a browser, the following output will get displayed.
This feature in LESS allows the addition of values to comma or space separated list from multiple properties using a single property. It can be used for background and transform properties.
The following table describes the two types of functions supported by the Merge feature.
Sr.No. | Types & Description |
---|---|
1 | Comma
It adds property value at the end. |
2 | Space
It adds property value with space. |
In this chapter, let us understand how Parent Selectors work. It is possible to reference the parent selector by using the &(ampersand) operator. Parent selectors of a nested rule is represented by the & operator and is used when applying a modifying class or pseudo class to an existing selector.
The following table shows the types of parent selector −
Sr.No. | Types & Description |
---|---|
1 | Multiple &
The & will represent the nearest selector and also all the parent selectors. |
2 | Changing Selector Order
Prepending a selector to the inherited (parent) selectors is useful when selector ordering is changed. |
3 | Combinatorial Explosion
The & can also produce all the possible permutation of selectors in a list separated by commas. |
The following example demonstrates the use of parent selector in the LESS file −
<!doctype html> <head> <link rel = "stylesheet" href = "style.css" type = "text/css" /> <title>Parent Selector</title> </head> <body> <h2>Welcome to Howcodex</h2> <ul> <li><a>SASS</a></li> <li><a>LESS</a></li> </ul> </body> </html>
Next, create the style.less file.
a { color: #5882FA; &:hover { background-color: #A9F5F2; } }
You can compile the style.less file to style.css by using the following command −
lessc style.less style.css
Execute the above command; it will create the style.css file automatically with the following code −
a { color: #5882FA; } a:hover { background-color: red; }
In the above example, & refers to selector a.
Follow these steps to see how the above code works −
Save the above html code in the parent_selector1.htm file.
Open this HTML file in a browser, the following output will get displayed.
The Parent selectors operator has many uses like, when you need to combine the nested rule's selectors in other way than the default. Another typical use of & is to generate class names repeatedly. For more information click here.
Misc functions consist of a group of functions of a different kind.
The following table lists all the types of misc functions −
Sr.No. | Functions & Description |
---|---|
1 | color
It is a string which represents colors. |
2 | image - size
It is used to examine the dimension of the image from the file. |
3 | image - width
It examines the width of the image from the file. |
4 | image - height
It examines the height of the image from the file. |
5 | convert
A number is converted from one unit to another. |
6 | data - uri
Data uri is uniform resource identifier (URI) schema which gets a resource inline on webpages. |
7 | default
Default function returns true only when it is available inside the guard condition and does not match with any other mixin. |
8 | unit
Default function returns true only when it is available inside the guard condition and does not match with any other mixin |
9 | get - unit
get - unit function returns its unit where the argument is present with number and units. |
10 | svg - gradient
svg-gradient is a transition of one color to another. It can add many colors to the same element. |
Less supports some of the string functions as listed below −
The following table describes the above string functions along with description.
Sr.No. | Types & Description | Example |
---|---|---|
1 | Escape It encodes a string or information by using URL encoding on special characters. You could not encode some characters such as , , / , ? , @ , & , + , ~ , ! , $ , ' and some characters you can encode such as \ , # , ^ , ( , ) , { , } , : , > , < , ] , [ and =. |
escape("Hello!! welcome to Howcodex!") It outputs escaped string as − Hello%21%21%20welcome%20to%20Howcodex%21 |
2 | e It is a string function which uses string as parameter and returns the information without quotes. It is a CSS escaping which uses ~"some content" escaped values and numbers as parameters. |
filter: e("Hello!! welcome to Howcodex!"); It outputs escaped string as − filter: Hello!! welcome to Howcodex!; |
3 | % format This function formats a string. It can be written with the following format − %(string, arguments ...) |
format-a-d: %("myvalues: %a myfile: %d", 2 + 3, "mydir/less_demo.less"); It outputs the formatted string as − format-a-d: "myvalues: 5 myfile: "mydir/less_demo.less""; |
4 | replace It is used to replace the text within a string. It uses some parameters −
|
replace("Welcome, val?", "val\?", "to Howcodex!"); It replaces the string as − "Welcome, to Howcodex!" |
LESS consists of list functions which are used to specify length of the list and position of the value in the list.
Following table lists the List functions used in LESS −
Sr.No. | Function & Description |
---|---|
1 | Length
It will take a comma or space separated list of values as parameter. |
2 | Extract
It will return the value at a specified position in a list. |
Math functions includes methods which are used for performing numeric operations such as round, square root, power value, modulus, percentage, etc.
Following table shows Math Functions used in LESS −
Sr.No. | Function & Description | Example |
---|---|---|
1 | ceil It rounds up the number to next highest integer. |
ceil(0.7) it round the number to − 1 |
2 | floor It rounds down the number to next lowest integer. |
floor(3.3) it round the number to − 3 |
3 | percentage It transforms the floating point number to percentage string. |
percentage(0.2) it converts the number to percentage string as − 20% |
4 | round It rounds a floating point number. |
round(3.77) it converts the number to the rounding value as − 4 |
5 | sqrt It returns the square root of a number. |
sqrt(25) it defines the square root of a number as − 5 |
6 | abs It provides the absolute value of a number. |
abs(30ft) it displays the absolute value as − 30ft |
7 | sin It returns radians on numbers. |
sin(2) it calculates the sine value as − 0.90929742682 |
8 | asin It specifies arcsine (inverse of sine) of a number which returns value between -pi/2 and pi/2. |
asin(1) it calculates the asin value as − 1.5707963267948966 |
9 | cos It returns cosine of the specified value and determines radians on numbers without units. |
cos(2) it calculates the cos value as − -0.4161468365471424 |
10 | acos It specifies arccosine (inverse of cosine) of a number which returns value between 0 and pi. |
acos(1) it calculates the acos value as − 0 |
11 | tan It specifies tangent of the number. |
tan(60) it calculates the tan value as − 0.320040389379563 |
12 | atan It specifies arctangent (inverse of tangent) of a specified number. |
atan(1) it displays atan value as − 0.7853981633974483 |
13 | pi It returns the pi value. |
pi() it determines the pi value as − 3.141592653589793 |
14 | pow It specifies the value of first argument raised to the power of second argument. |
pow(3,3) it specifies the power value as − 27 |
15 | mod It returns modulus of first argument with respect to the second argument. It also handles negative and floating point numbers. |
mod(7,3) it returns the modulus value as − 1 |
16 | min It specifies the smallest value of one or more arguments. |
min(70,30,45,20) it returns the minimum value as − 20 |
17 | max It specifies the highest value of one or more arguments. |
max(70,30,45,20) it returns the maximum value as − 70 |
In this chapter, we will understand the importance of Type Functions in LESS. They are used to determine the type of the value.
The following table shows the Type Functions used in LESS.
Sr.No. | Type Functions & Description | Example |
---|---|---|
1 | isnumber It takes a value as parameter and returns true, if it's a number or false otherwise. |
isnumber(1234); // true isnumber(24px); // true isnumber(7.8%); // true isnumber(#fff); // false isnumber(red); // false isnumber("variable"); // false isnumber(keyword); // false isnumber(url(...)); // false |
2 | isstring It takes a value as parameter and returns true, if it's a string or false otherwise. |
isstring("variable"); // true isstring(1234); // false isstring(24px); // false isstring(7.8%); // false isstring(#fff); // false isstring(red); // false isstring(keyword); // false isstring(url(...)); // false |
3 | iscolor It takes a value as parameter and returns true, if value is a color or false if it's not. |
iscolor(#fff); // true iscolor(red); // true iscolor(1234); // false iscolor(24px); // false iscolor(7.8%); // false iscolor("variable"); // false iscolor(keyword); // false iscolor(url(...)); // false |
4 | iskeyword It takes a value as parameter and returns true, if value is a keyword or false if it's not. |
iskeyword(keyword); // true iskeyword(1234); // false iskeyword(24px); // false iskeyword(7.8%); // false iskeyword(#fff); // false iskeyword(red) ; // false iskeyword("variable");// false iskeyword(url(...)); // false |
5 | isurl It takes a value as parameter and returns true, if value is a url or false if it's not. |
isurl(url(...)); // true isurl(keyword); // false isurl(1234); // false isurl(24px); // false isurl(7.8%); // false isurl(#fff); // false isurl(red) ; // false isurl("variable"); // false |
6 | ispixel It takes a value as parameter and returns true, if value is a number in pixels or false otherwise. |
ispixel(24px); // true ispixel(1234); // false ispixel(7.8%); // false ispixel(keyword); // false ispixel(#fff); // false ispixel(red) ; // false ispixel("variable"); // false ispixel(url(...)); // false |
7 | isem It takes a value as parameter and returns true, if value is an em value or false if it's not. |
isem(0.5em); // true isem(1234); // false isem(24px); // false isem(keyword); // false isem(#fff); // false isem(red) ; // false isem("variable"); // false isem(url(...)); // false |
8 | ispercentage It takes a value as parameter and returns true, if value is in percentage or returns false, if value is not in percentage. |
ispercentage(7.5%); // true ispercentage(url(...)); // false ispercentage(keyword); // false ispercentage(1234); // false ispercentage(24px); // false ispercentage(#fff); // false ispercentage(red) ; // false ispercentage("variable"); // false |
9 | isunit It returns true if a value is a number in specified units provided as parameter or it will return false if value is not a number in specified units. |
isunit(10px, px); // true isunit(5rem, rem); // true isunit(7.8%, '%'); // true isunit(2.2%, px); // false isunit(24px, rem); // false isunit(48px, "%"); // false isunit(1234, em); // false isunit(#fff, pt); // false isunit("mm", mm); // false |
10 | isruleset It takes a value as parameter and returns true, if value is a ruleset or false otherwise. |
@rules: { color: green; } isruleset(@rules); // true isruleset(1234); // false isruleset(24px); // false isruleset(7.8%); // false isruleset(#fff); // false isruleset(blue); // false isruleset("variable"); // false isruleset(keyword); // false isruleset(url(...)); // false |
LESS provides number of useful color functions to alter and manipulate colors in different ways. LESS supports some of the Color Definition Functions as shown in the table below −
Sr.No. | Function & Description | Example |
---|---|---|
1 | rgb It creates color from red, green and blue values. It has following parameters −
|
rgb(220,20,60) it converts color with rgb values as − #dc143c |
2 | rgba It determines color from red, green, blue and alpha values. It has the following parameters −
|
rgba(220,20,60, 0.5) it converts color object with rgba values as − rgba(220, 20, 60, 0.5) |
3 | argb It defines hex representation of color in #AARRGGBB format. It uses the following parameter −
|
argb(rgba(176,23,31,0.5)) it returns the argb color as − #80b0171f |
4 | hsl It generates the color from hue, saturation and lightness values. It has following parameters −
|
hsl(120,100%, 50%) it returns the color object using HSL values as − #00ff00 |
5 | hsla It generates the color from hue, saturation, lightness and alpha values. It has the following parameters −
|
hsla(0,100%,50%,0.5) it specifies the color object using HSLA values as − rgba(255, 0, 0, 0.5); |
6 | hsv It produces the color from hue, saturation and value values. It contains following parameters −
|
hsv(80,90%,70%) it converts color object with hsv values as − #7db312 |
7 | hsva It produces the color from hue, saturation, value and alpha values. It uses the following parameters −
|
hsva(80,90%,70%,0.6) it specifies color object with hsva values as − rgba(125, 179, 18, 0.6) |
In this chapter, we will understand the importance of Color Channel Functions in LESS. LESS supports few in-built functions which set value about a channel. The channel set the value depending on the color definition. The HSL colors have hue, saturation and lightness channel and the RGB color have red, green and blue channel. The following table lists out all the color channel functions −
Sr.No. | Function & Description | Example |
---|---|---|
1 | hue In HSL color space, the hue channel is extracted off the color object. |
background: hue(hsl(75, 90%, 30%)); It compiles in the CSS as shown below − background: 75; |
2 | saturation In HSL color space, the saturation channel is extracted off the color object. |
background: saturation(hsl(75, 90%, 30%)); It compiles in the CSS as shown below − background: 90%; |
3 | lightness In HSL color space, the lightness channel is extracted off the color object. |
background: lightness(hsl(75, 90%, 30%)); It compiles in the CSS as shown below − background: 30%; |
4 | hsvhue In HSV color space, the hue channel is extracted off the color object. |
background: hsvhue(hsv(75, 90%, 30%)); It compiles in the CSS as shown below − background: 75; |
5 | hsvsaturation In HSL color space, the saturation channel is extracted off the color object. |
background: hsvsaturation(hsv(75, 90%, 30%)); It compiles in the CSS as shown below − background: 90%; |
6 | hsvvalue In HSL color space, the value channel is extracted off the color object. |
background: hsvvalue(hsv(75, 90%, 30%)); It compiles in the CSS as shown below − background: 30%; |
7 | red The red channel is extracted off the color object. |
background: red(rgb(5, 15, 25)); It compiles in the CSS as shown below − background: 5; |
8 | green The green channel is extracted off the color object. |
background: green(rgb(5, 15, 25)); It compiles in the CSS as shown below − background: 15; |
9 | blue The blue channel is extracted off the color object. |
background: blue(rgb(5, 15, 25)); It compiles in the CSS as shown below − background: 25; |
10 | alpha The alpha channel is extracted off the color object. |
background: alpha(rgba(5, 15, 25, 1.5)); It compiles in the CSS as shown below − background: 2; |
11 | luma luma value is calculated off a color object. |
background: luma(rgb(50, 250, 150)); It compiles in the CSS as shown below − background: 71.2513323%; |
12 | luminance The luma value is calculated without gamma correction. |
background: luminance(rgb(50, 250, 150)); It compiles in the CSS as shown below − background: 78.53333333%; |
LESS provides number of useful operation functions to alter and manipulate colors in different ways and take parameters in the same units. LESS supports some of the Color Operation Functions as shown in the table below −
Sr.No. | Directives & Description |
---|---|
1 | saturate
It varies the intensity or saturation of a color in the element. |
2 | desaturate
It decreases the intensity or saturation of a color in the element. |
3 | lighten
It increases the lightness of a color in the element. |
4 | darken
It varies the intensity or saturation of a color in the element. |
5 | fadein
It increases the opacity for selected elements. |
6 | fadeout
It decreases the opacity for selected elements. |
7 | fade
It is used to set the transparency of a color for selected elements. |
8 | spin
It is used to rotate the angle of a color for selected elements. |
9 | mix
It mixes the two colors along with the opacity. |
10 | tint
It mixes the color with white as you decrease the proportion of the color. |
11 | shade
It mixes the color with black as you decrease the proportion of the color. |
12 | greyscale
It discards the saturation from a color in the selected elements. |
13 | contrast
It sets the contrast for the colors in the element. |
In this chapter, we will understand the Color Blending Functions in LESS. These are similar operations used in image editors like Photoshop, Fireworks or GIMP, which matches your CSS colors to your images.
The following table shows the color blending functions used in LESS.
Sr.No. | Functions & Description |
---|---|
1 | multiply
It multiplies two colors and returns a resultant color. |
2 | screen
It takes two colors and returns a brighter color. It works opposite of multiply function. |
3 | overlay
It generates result by combining the effect of multiply and screen. |
4 | softlight
It works similar to overlay but it uses only a part of the color, which soft-highlights the other color. |
5 | hardlight
It works similar to overlay but the role of the colors reversed. |
6 | difference
It subtracts the second input color from the first input color. |
7 | exclusion
It works similar to difference function but with lower contrast. |
8 | average
It computes the average of two input colors on a per-channel (RGB) basis. |
9 | negation
It works opposite to difference function, which subtracts first color from second color. |
Using the command line, we can compile the .less file to .css.
The following command is used to install lessc with npm(node package manager) to make the lessc available globally.
npm install less -g
You can also add a specific version after the package name. For example npm install less@1.6.2 -g
The following command is used to install the latest version of lessc in your project folder.
npm i less -save-dev
It is also added to the devDependencies in your project package.json.
It is tagged as beta when the lessc structure is published to npm Here, the new functionality is developed periodically. less -v is used to get the current version.
The commit - ish is to be specified, when we proceed to install an unpublished version of lessc and the instructions need to be followed for identifying a git URL as a dependency. This will ensure that you are using the correct version of leesc for your project.
bin/lessc includes binary in the repository. It works with Windows, OS X and nodejs on *nix.
Input is read from stdin when source is set to dash or hyphen(-).
lessc [option option = parameter ...]
For instance, we can compile .less to .css by using the following command −
lessc stylesheet.less stylesheet.css
We can compile .less to .css by and minify the result using the following command.
lessc -x stylesheet.less stylesheet.css
Following table lists out options used in command line usage −
Sr.No. | Options & Description | Command |
---|---|---|
1 | Help Help message is displayed with the options available. |
lessc -help lessc -h |
2 | Include Paths It includes the available paths to the library. These paths can be referenced simply and relatively in the Less files. The paths in windows are separated by colon(:) or semicolon(;). |
lessc --include-path = PATH1;PATH2 |
3 | Makefile It generates a makefile import dependencies list to stdout as output. |
lessc -M lessc --depends |
4 | No Color It disables colorized output. |
lessc --no-color |
5 | No IE Compatibility It disables IE compatibility checks. |
lessc --no-ie-compat |
6 | Disable Javascript It disables the javascript in less files. |
lessc --no-js |
7 | Lint It checks the syntax and reports error without any output. |
lessc --lint lessc -l |
8 | Silent It forcibly stops the display of error messages. |
lessc --silent lessc -s |
9 | Strict Imports It force evaluates imports. |
lessc --strict-imports |
10 | Allow Imports from Insecure HTTPS Hosts It imports from the insecure HTTPS hosts. |
lessc --insecure |
11 | Version It displays the version number and exits. |
lessc -version lessc -v |
12 | Compress It helps in removing the whitespaces and compress the output. |
lessc -x lessc --compress |
13 | Source Map Output Filename It generates the sourcemap in less. If sourcemap option is defined without filename then it will use the extension map with the Less file name as source. |
lessc --source-map lessc -source-map = file.map |
14 | Source Map Rootpath Rootpath is specified and should be added to Less file paths inside the sourcemap and also to the map file which is specified in your output css. |
lessc --source-map-rootpath = dev-files/ |
15 | Source Map Basepath A path is specified which has to be removed from the output paths. Basepath is opposite of the rootpath option. |
lessc --source-map-basepath = less-files/ |
16 | Source Map Less Inline All the Less files should be included in the sourcemap. |
lessc --source-map-less-inline |
17 | Source Map Map Inline It specifies that in the output css the map file should be inline. |
lessc --source-map-map-inline |
18 | Source Map URL A URL is allowed to override the points in the map file in the css. |
lessc --source-map-url = ../my-map.json |
19 | Rootpath It sets paths for URL rewriting in relative imports and urls. |
lessc -rp=resources/ lessc --rootpath=resources/ |
20 | Relative URLs In imported files, the URL are re-written so that the URL is always relative to the base file. |
lessc -ru lessc --relative-urls |
21 | Strict Math It processes all Math function in your css. By default, it's off. |
lessc -sm = on lessc --strict-math = on |
22 | Strict Units It allows mixed units. |
lessc -su = on lessc --strict-units = on |
23 | Global Variable A variable is defined which can be referenced by the file. |
lessc --global-var = "background = green" |
24 | Modify Variable This is unlike global variable option; it moves the declaration at the end of your less file. |
lessc --modify-var = "background = green" |
25 | URL Arguments To move on to every URL, an argument is allowed to specify. |
lessc --url-args = "arg736357" |
26 | Line Numbers Inline source-mapping is generated. |
lessc --line-numbers = comments lessc --line-numbers = mediaquery lessc --line-numbers = all |
27 | Plugin It loads the plugin. |
lessc --clean-css lessc --plugin = clean-css = "advanced" |
Less is used in the browser when you want to compile the Less file dynamically when needed and not on the serverside; this is because less is a large javascript file.
To begin with, we need to add the LESS script to use LESS in the browser −
<script src = "less.js"></script>
To find the style tags on page, we need to add the following line on the page. It also creates the style tags with the compiled css.
<link href = "styles.less" rel = "stylesheet/less" type = "text/css"/>
Before the script tag, options can be set on the less object programmatically. It will affect all the programmatic usage of less and the initial link tags.
For instance, we can set option as followed −
<script> less = { env: "development" }; </script> <script src = "less.js"></script>
We can also set the option in another format on the script tag as specified below −
<script> less = { env: "development" }; </script> <script src = "less.js" data-env = "development"></script>
You can also add these options to the link tags.
<link data-dump-line-numbers = "all" data-global-vars = '{ "var": "#fff", "str": "\"quoted\"" }' rel = "stylesheet/less" type = "text/css" href = "less/style.less">
The points that need to be considered for attribute options are −
window.less < script tag < link tag are the importance level.
The data attributes cannot be written in camel case; the link tag option are represented as time options.
The data attributes with non-string values should be JSON valid.
The watch mode can be enabled by setting the env option to development and call the less.watch() after the less.js file is added. If you want the watch mode to be enabled on a temporary basis, then add #!watch to the URL.
<script>less = { env: 'development'};</script> <script src = "less.js"></script> <script>less.watch();</script>
Run time modification of LESS variable is enabled. LESS file is recompiled when new value is called. The following code shows the basic usage of modify variables −
less.modifyVars({ '@buttonFace': '#eee', '@buttonText': '#fff' });
We can add the option !dumpLineNumbers:mediaquery to the url or dumpLineNumbers option as mentioned above. The mediaquery option can be used with FireLESS(It display the original LESS file name and line number of LESS-generated CSS styles.)
Before loading the script file less.js, options have to be set in a global less object.
<script> less = { env: "development", logLevel: 2, async: false, fileAsync: false, poll: 1000, functions: {}, dumpLineNumbers: "comments", relativeUrls: false, globalVars: { var1: '"string value"', var2: 'regular value' }, rootpath: ":/a.com/" }; </script> <script src = "less.js"></script>
async − It is a Boolean type. The imported files are requested whether with the option async or not. By default, it is false.
dumpLineNumbers − It is a string type. In the output css file, the source line information is added when the dumpLineNumbers is set. It helps in debugging the particular rule came from.
env − It is a string type. The env may run on development or production. Development is set automatically when the document URL starts with file:// or it is present in your local machine.
errorReporting − When the compilation fails, the error reporting method can be set.
fileAsync − It is a Boolean type. When a page is present with a file protocol then it can request whether to import asynchronously or not.
functions − It is object type.
logLevel − It is a number type. It displays the logging level in the javascript console.
2 : Information and errors
1 : Errors
0 : Nothing
poll − In the watch mode, the time displays in milliseconds between the polls. It is an integer type; by default, it is set to 1000.
relativeUrls − The URLs adjust to be relative; by default, this option is set as false. This means that the URLs are relative already to the entry less file. It is a Boolean type.
globalVars − Inserts the list of global variables into the code. The string type variable should be included in quotes
modifyVars − It is unlike the global variable option. It moves the declaration at the end of your less file.
rootpath − It sets paths at the start of every URL resource.
useFileCache − Uses per session file cache. The cache in less files is used to call the modifyVars where all the less files will not retrieve again.
LESS is cross-browser friendly. It supports modern browsers such as Google Chrome, Mozilla Firefox, Safari and Internet Explorer and allows reusing CSS elements and write LESS code with the same semantics. You must be careful about the performance implications while using LESS on the client side and while displaying the JavaScript to avoid any cosmetic issues such as
Compile the LESS files on the server side to improve the performance levels of the website.
PhantomJS does not implement Function.prototype.bind function, so you need to use es5 shim JavaScript engine to run under PhantomJS. Users can make adjustments with variables to affect the theme and show them in real time by using the client side LESS in the production.
If you want to run LESS in older browsers, then use the es-5 shim JavaScript engine which adds JavaScript features that LESS supports. You can use attributes on the script or link tags by using JSON.parse which must be supported by the browser.
In this chapter, we will understand how a Plugin can be uploaded to expand the functionality of the site. Plugins can be used to make your work easier.
To install plugin using command line, you first need to install the lessc plugin. The plugin can be installed using less-plugin at the beginning. The following command line will help you install the clean-css plugin −
npm install less-plugin-clean-css
Directly, you can use the installed plugin by using the following command −
lessc --plugin = path_to_plugin = options
In Node, the plugin is required and it is pass in an array as an option plugin to the less.
var pluginName = require("pluginName"); less.render(myCSS, { plugins: [pluginName] }) .then(function(output) { }, function(error) { });
Before the less.js script, the plugin author should include the javascript file in the page.
<script src = "plugin.js"></script> <script> less = { plugins: [plugin] }; </script> <script src = "less.min.js"></script>
The following table lists out the plugins available in LESS.
Sr.No. | Plugins & Description |
---|---|
1 | Autoprefixer
It is used to add prefixes to CSS after translation from LESS. |
2 | CSScomb
It helps to improve the maintenance of your stylesheet. |
3 | clean-css
It minifies the CSS output from LESS. |
4 | CSSWring
It compresses or minify the CSS output from LESS. |
5 | css-flip
It is used to generate the CSS from left-to-right(LTR) or right-to-left(RTL). |
6 | functions
It writes the function of LESS in the LESS itself. |
7 | glob
It is used to import multiple files. |
8 | group-css-media-queries
It does the post-processing for Less. |
9 | inline-urls
Automatically converts the URL to data uri. |
10 | npm-import
It imports from npm package for less. |
11 | pleeease
It is used to postprocess Less. |
12 | rtl
LESS is reversed from ltr(left-to-right) to rtl(right-to-left). |
Sr.No. | Importers & Description |
---|---|
1 | Bootstrap
Bootstrap LESS code is imported before the custom LESS code. |
2 | Bower Resolve
LESS files are imported from the Bower packages. |
3 | Cardinal CSS for less.js
Before the custom LESS code, the LESS code for Cardinal is imported. |
4 | Flexbox Grid
Most commonly imported Framework or library importer. |
5 | Flexible Grid System
It imports the Flexible Grid System. |
6 | Ionic
It imports the ionic framework. |
7 | Lesshat
It imports the Lesshat mixins. |
8 | Skeleton
It imports the skeleton less code. |
Sr.No. | Importers & Description |
---|---|
1 | advanced-color-functions
It is used to find more contrasting colors. |
2 | cubehelix
Using gamma correction value of 1, the cubehelix function can return a color between the two colors. |
3 | lists
This lists manipulation functions library. |
LESS allow an author to combine with less.
{ install: function(less, pluginManager) { }, setOptions: function(argumentString) { }, printUsage: function() { }, minVersion: [2, 0, 0] }
pluginManager provides a holder which can add file managers, post processors or visitors.
setOptions function passes the string.
printUsage function is used to explain the options.
The main point of programmatic usage in the LESS is less.render function. This function uses the following format in LESS −
less.render(input_data, options) .then(function(output) { //code here }, function(error) { });
the function can also be written in the following way −
less.render(css, options, function(error, output) {})
The options is an optional argument which returns a promise when you don't specify the callback and returns a promise when you specify the callback. You can display the file by reading it into string and set the filename fields of the main file.
The sourceMap option allows to set sourcemap options such as sourceMapURL, sourceMapBasepath, sourceMapRootpath, outputSourceFiles and sourceMapFileInline. The point that needs to be considered here is that the sourceMap option is not available for the less.js.
You can gain access to the log by adding a listener as shown in the below format −
less.logger.addListener({ debug: function(message) { }, info: function(message) { }, warn: function(message) { }, error: function(message) { } });
The above defined functions are optional. If an error is displayed, then it will pass the error to callback or promise present in the less.render.
In this chapter, we will understand the importance of online compilers in LESS. Online compilers are used to compile the less code into css code. Online compilers tools easily help to generate the css code. Following are the available online less compilers −
Following are the available Online Web IDEs with Less support.
Sr.No. | Online Web IDEs & Description |
---|---|
1 | CSSDeck Labs
This is a place where you can easily create testcases that involve HTML, CSS, JS code. |
2 | CodePen This is a playground for the frontend web. |
3 | Fiddle Salad
This is a place where you can add an existing code in the environment. |
4 | JS Bin
This helps Javascript and CSS code. |
5 | jsFiddle
This is an online web editor. |
In this chapter, we will understand the GUIs for LESS. You can use different LESS tools for your platform. For command line usage and tools click this link.
The following table lists the GUI compilers that supports cross platform.
Sr.No. | Tools & Description |
---|---|
1 | Crunch 2!
It supports across platforms like Windows, Mac and Linux. It provides editor with integrated compiling. |
2 | Mixture It is a rapid prototyping and static site generation tool used by designers and developers. It is quick, efficient and works well with your editor. It brings together a collection of awesome tools and best practices. |
3 | SimpLESS
It is a minimalistic LESS compiler. It provides drag, drop and compile functionality. SimpLESS supports prefixing your CSS by using prefixr which is the unique feature of SimpLESS. It is built on Titanium platform. |
4 | Koala
It is used to compile LESS, SASS and CoffeeScript. It provides features like compile error notification supports and compile options supports. |
The following table lists the GUI compilers that support Windows platform.
Sr.No. | Tools & Description |
---|---|
1 | Prepros
It a tool that compiles LESS, SASS, Compass, Stylus, Jade and many more. |
2 | WinLess
Initially it was a clone of LESS.app, it has several settings and takes more feature complete approach. It supports starting with command line arguments. |
The following table lists the GUI compilers that supports OS X platform.
Sr.No. | Tools & Description |
---|---|
1 | CodeKit
t is successor of LESS.app and supports LESS among many other processing languages like SASS, Jade, Markdown and more. |
2 | LiveReload
It edits CSS and changes images instantly. SASS, LESS, CoffeeScript and others work well. |
The following table lists the GUI compilers that supports OS X platform.
Sr.No. | Tools & Description |
---|---|
1 | Plessc
It is gui frontend for lessc. It has features like log viewer, auto compile, opening the LESS file with the chosen editor and sourcemap support. |
In this chapter, we will understand the importance of editors and plugins in LESS. An Editor is a system or program which allows a user to edit text. Plugin is a piece of software that is used to expand the functionality of the site.
Let us now discuss editors and IDEs for LESS.
Sr.No. | Editors and IDEs & Description |
---|---|
1 | Crunch!
It supports cross-platforms like Windows, Mac and Linux. It provides editor with integrated compiling. |
2 | Mindscape Web Workbench
It provide CoffeeScript, SASS, Compass and LESS editing and makes modern web development easy in Visual Studio. |
3 | NetBeans
It is an open-source Java-based IDE. This helps in the quick development of your desktop, mobile and web applications as well as HTML5 applications that involve HTML, JavaScript and CSS. |
4 | TextMate
It is a general purpose graphical text editor for Mac OS X. It features declarative customizations, recordable macros, snippets, shell integration, open documents tabs and an extensible bundle system. |
5 | Vim
The vim bundle adds functionalities like indenting, highlighting and auto completion for the dynamic stylesheet language LESS. |
6 | Emacs
It contains less-css-model that provides an Emacs mode for LESS CSS (lesscss.org); Emacs supports compile-on-save. |
7 | jetBrains WebStorm and PhpStorm
WebStrom is a lightweight and powerful IDE. It is perfectly equipped for complex client-side and server development with Node.js. PhpStorm is an PHP IDE, which supports deep code understanding, and provides top-notch coding assistance and support for all major tools and frameworks. |
8 | Brackets
It is a lightweight, powerful and an open-source code editor that helps web designers and front-end developers. |
9 | CodeLobster
It is a portable integrated development environment (IDE) primarily for PHP. It also supports HTML, CSS and JavaScript development and plugins are available for Drupal, WordPress, Smarty, Joomla, JQuery, Facebook, Codeigniter, Yii and CakePHP. |
10 | KineticWing IDE
It is a quick, clean, lightweight and portable IDE. It is a full-size development suite that helps you work smart and fast. |
11 | nodeMirror
It is an open-source and easily customizable IDE. It utilizes CodeMirror.net, pty.js and other libraries. |
12 | HTML-Kit Tools
This is a modern web editor for HTML5, CSS3, JavaScript and more. With this, you can edit, preview, validate publish and manage projects from modern standards compliant editor. |
The sublime text provides different options for LESS as listed in the following table −
Sr.No. | Options & Description |
---|---|
1 | Less-sublime
LESS syntax for sublime text provides syntax highlighting for .less files, along with snippets. |
2 | Sublime-Less-to-CSS
Sublime text 2 and 3 plugin to compile .less files to CSS when you save. It requires lessc installed on PATH. |
3 | Less-build-sublime
LESS build system for sublime text 2 which provides two build systems for LESS files, both minified and non-minified. |
4 | SublimeOnSaveBuild It is a simple plugin for sublime text 2 to trigger a build when you click Save. Works well with pre-processors like LESS, Compass and any others. |
Eclipse has two plugins for LESS as listed in the following table −
Sr.No. | Plugins & Description |
---|---|
1 | Eclipse Less Plugin
By extending the Eclipse IDE, this plugin provides useful features to edit and compile LESS stylesheets. |
2 | Transpiler Plugin
This Eclipse plugin automatically transpiles your files like LESS, SASS, CoffeeScript, etc. |
Visual Studio has the following different options for LESS −
Sr.No. | Options & Description |
---|---|
1 | CSS Is Less
This extension makes LESS files open with CSS language service. |
2 | Web Essentials 2012
This extension lets you perform common tasks much easier and adds useful features to Visual studio for web developers. |
3 | Web Essentials 2013
It extends Visual Studio with a lot of new features which are not specific to a specific language or editor. |
4 | Web Tools 2013
This helps you in the development tasks that involve ASP.NET |
The following points need to be considered while working with Dreamweaver.
It is an Adobe application used by web designers and developers to create applications and websites.
Web designers use Dreamweaver for creating website prototypes.
DMXzone Less CSS Compiler makes all the LESS CSS powers directly in Dreamweaver.
The following points needs to be considered while working on Notepad++.
Notepad++ is a free text editor and source code editor which supports tabbed editing, i.e., working with multiple open files in a single window.
LESS for Notepad++ is an xml file that provides syntax highlighting or coloring for .less files. To get more information, click on this link.
To install Notepad++ click this link.
Following are the Node.js compilers used for LESS.
Grunt is a Node task runner. It will compile your stylesheets every time you commit changes to your LESS files.
assemble-less is a powerful grunt plugin for compiling LESS file to CSS. The less task pulls JSON and Lo - dash(underscore) template for defining the LESS bundles, UI components, compressed stylesheets or themes.
It is LESS plugin for Gulp. gulp-minify-css is used to minify your CSS. gulp-sourcemaps is used to generate the sourcemaps library.
It is an open-source tool which is built on LESS and helps in optimizing your CSS code. It keeps the CSS code error free, clean and manageable.
It is a .less file watcher. It contains dependency tracking and Cross-platform notification.
It is used to allow the processing for connect JS framework of LESS files. It compiles source file on request and cache the compiled data for next request.
Following are a few othertechnologies that help you compile a LESS code.
You can download the wro4j-runner.jar and can compile your LESS code in CSS by using the following command −
java -jar wro4j-runner-1.5.0-jar-with-dependencies.jar --preProcessors lessCss
You can visit the following link to know more about Wro4j Runner CLI
This module is used to parse and compile the LESS file into CSS file. Following is the command used to compile −
lessp.pl styles.less > styles.css
You can visit the following link to know more about CSS::LESSp
Following is the command line compiler that will run on windows.
cscript //nologo lessc.wsf input.less [output.css] [-compress]
OR
lessc input.less [output.css] [-compress]
You can visit the following link to know more about Less.js for windows
The following is a command line compiler to run dotless for windows.
dotless.Compiler.exe [-switches] <inputfile> [outputfile]
You can visit the following link to know more about dotless
LESS supports some of the UI/Theme frameworks as listed in the following table −
Sr.No. | Framework & Description |
---|---|
1 | 1pxdeep
It is flat Bootstrap 3 theme that provides powerful color scheme controls. |
2 | Bootflat
It is an open-source framework based on Bootstrap. |
3 | BootPress
It is a PHP framework based on flat file CMS |
4 | Bootstrap
It is powerful mobile first front-end framework for faster and easier web development. |
5 | Bootstrap a11y theme
It provides easy accessibility for web development. |
6 | Bootswatch
It is an open-source theme that provides free themes for Bootstrap. |
7 | Cardinal
It is mobile-first CSS framework that allows maintaining CSS for responsive websites, user interfaces, and applications. |
8 | CSSHorus
It is a library that provides easy development of mobile websites. |
9 | Flat UI Free
It is based on Bootstrap 3 which contains basic and complex components and provides theme design for Bootstrap. |
10 | frontsize
It is a frontend framework that contains a set of tools to build widgets. |
11 | InContent It specifies the description of the image using CSS3 and SASS/LESS. |
12 | Ink
It creates responsive web interfaces. |
13 | JBST
It is powerful theme framework used for creating child themes for WordPress and used as standalone website builder. |
14 | KNACSS
It is used to develop HTML/CSS projects by using responsive and extensible style sheets. |
15 | Kube
It is CSS framework used for professional designers and developers. |
16 | Metro UI CSS
It is a frontend framework used for creating Windows Metro Style on the projects. |
17 | Pre
It is CSS framework that uses LESS. |
18 | prelude
It is frontend CSS framework that uses LESS. |
19 | Schema
It is a light and responsive framework which helps to build complex websites. |
20 | Semantic UI
It is a user interface framework that creates responsive layouts using HTML. |
21 | UIkit
It is a frontend framework which includes HTML, CSS, and JS components and easy to use and develop web applications. |
22 | ngBoilerplate It is grunt based build system used for AngularJS projects. |
23 | less-rail
It is a dynamic stylesheet language that uses Less.js for Rails projects. |
24 | Wee
It is a frontend framework which contains HTML, CSS and JavaScript bootstrap components for developing responsive web projects. |
LESS supports grid systems frameworks as listed in the following table −
Sr.No. | Framework & Description |
---|---|
1 | Flexible Grid System
It is a CSS framework which creates web projects in a flexible way. |
2 | adaptGrid
It is a responsive grid system for developing web applications. |
3 | Fluidable
It is lightweight responsive grid system based on LESS preprocessor. |
4 | Golden Grid System
It is grid system for responsive design. |
5 | LESS Zen Grid
It is used for solving sub pixel rounding issue. |
6 | Order.less
It is a LESS library used for alignment, grid system and modular scales. |
7 | responsibly
It is a customizable and standalone grid system. |
8 | Responsive Boilerplate
It is a lightweight grid system used to create responsive web design for the sites. |
9 | Semantic.gs
It is the default distribution of web browser to its operating system. |
LESS provides mixin libraries as listed in the following table −
Sr.No. | Framework & Description |
---|---|
1 | 3L
It provides newest CSS3 features for LESS preprocessor. |
2 | animate
It is a library used for browser animations used in the projects. |
3 | Clearless
It uses reusable LESS mixins without destroying the style and creating excessive size in stylesheets. |
4 | Css3LessPlease
It converts css3please.com to LESS mixins and element will get instant changes when you run the CSS. |
5 | CssEffects
It provides CSS style effects written as LESS mixins. |
6 | Cssowl
It is a mixin library which supports for LESS, SASS and Stylus. |
7 | cube.less
It is a 3D animated cube created using only CSS. |
8 | tRRtoolbelt.less
It is a library which provides mixins and functions for performing actions on LESS files. |
9 | est
It is based on LESS which allows to write LESS code more efficiently. |
10 | Hexagon
It creates CSS hexagons with size and color. |
11 | homeless
It is a mixin library that contains helpful functions for the Less.js. |
12 | LESS Elements It is a collection of mixins for the LESS preprocessor. |
13 | LESS Hat
It is a mixin library which helps in exporting CSS for all browsers and creates number of shadows, gradients and animations etc. |
14 | lessley
It is testing suite which is written in LESS. |
15 | LESS-bidi
It is a collection of LESS mixins which provides bi-directional styling without duplication of code. |
16 | LESS-Mix It is a mixin library written in LESS. |
17 | media-query-to-type
It is used for creating media queries which allows Internet Explorer 8 and below versions to access the content. |
18 | More-Colors.less
It provides variables for color manipulation while designing web applications. |
19 | more-less
It is a library which allows to write CSS code for cross browser compatibility. |
20 | More.less
It is a combination of Compass and Twitter Bootstrap which provides more to LESS by using CSS3 and cross browser mixins. |
21 | more-or-less
It provides powerful mixins for less.js. |
22 | normalize.less
It provides normalized CSS using LESS. |
23 | Oban
It is a collection of mixins which speeds up the development process of the web application. |
24 | Preboot
It is a set of LESS services that uses mixins and variables for writing better CSS and is formed from the Bootstrap. |
25 | prelude-mixins
It is a LESS mixin library. |
26 | Shape.LESS
It provides a number of mixins for specifying various shapes for the application. |