In this article we learn what less.js is and how to implement it.
LESS stands for Leaner CSS. LESS is a pre-processor. LESS extends the CSS language. In LESS we can declare variables. LESS runs inside nodes. In other words LESS is a CSS framework that extends our CSS, it adds more features like initializing variables, mixings, functions and many other technologies that makes CSS more maintainable.
Let's add a HTML page and name it home.htm. Then add a folder and name it style. In this folder we will add a CSS file and name it StyleSheet.css.
In style.css:
.Div { float:left; font-family: Georgia; font-size : 16px; background-color : black; color: #FFF; width:1000px; height: 40px; padding-top:10px; padding-left:30px; }
.DivOne { float:left; font-family: Georgia; font-size : 20px; background-color:black; color: #FFF; width:1000px; height: 40px; padding-top:10px; padding-left:30px; }
In Home.htm:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head> <link href="style/StyleSheet.css" rel="stylesheet" type="text/css"></link></head>
- <body> <div class="Div"> Pramod </div>
- <div style="clear:both; height:10px; width:10px;"></div>
- <div class="DivOne"> Ravi </div>
- </body></html>
Output
But what is new in less.js? We have done these things without using less.js. So I will share one amazing feature of LESS.
Variable Declaration
Suppose the client says to me, please replace the black with red in the background color. In this scenario I need to manually change the color code in all the CSS classes. That is a painful task for me. LESS provides a facility for declaring a variable. In LESS variables are case sensitive. In stylesheet.css I will declare a variable called bgcolor and set the color name to Red.
And replace the code "background-color : black" with "background-color : @bgcolor".
Let's make some changes in home.htm. In the link tag replace rel=”stylesheet” with rel="stylesheet/less".
- <link href="style/StyleSheet.css" rel="stylesheet/less" type="text/css"></link>
Add a reference of less.js and see the output.
- <script src="Scripts/less-1.7.5-min.js"></script>
Output
Note: Run it as a website, not as a htm file. The URL should be like http://localhost or http://mywebsite.com.
Variable Scope
LESS has two scopes, global and local. A variable that is declared outside a class definition is a global variable and its value is accessible and modifiable. A variable that is declared inside a function definition is local. A local variable is not accessible outside of the class.
I hope this article is helpful for you.
Thanks :)