Less CSS - SPLessons

Chapter 12

Less Scope

Less Scope

This chapter explains about Less Scope. This tutorial consists a snippet code explaining the main scheme of Less Scope.

Less scope is similar to that of a programming language. The scope concept in Less applies when variables and mixins are first searched locally and if not found, the compiler will search in the parent scope.

snippet code

The below snippet code explains the main scheme of using Less Scope.

@default-color: black;
/* Makes a tags red */
a {
color: @default-color;
@default-color: red;
}
/* h1s are still black */
h1 {
color: @default-color;
}

Below example explains the use of Less scope.
The below conceptual diagram represents the overall view about the example like creating .html and .less files in node js folder and compiling .less to .css.
Create a simple HTML file in the Nodejs folder as shown below.

Less_scope.html

<html>
<a href="#">Less scope</a>
<h1>Scope in Less is very similar to that of programming languages.</h1>
</html>

Create a Less file in the same Node js folder as shown below.

style.less

@default-color: black;
// Makes a tags red
a {
font-size: 30px;
color: @default-color;
@default-color: blue;
}
// H1s are still black
h1 {
font-weight: 300;
color: @default-color;
}
// Ignore, is for demo
body {
padding-top: 50px;
text-align: center;
background: rgb(213, 213, 246);
font-family: 'calibri light';
}

Compile the above Less code in command prompt using the below command.

lessc style.less style.css

By compiling the above Less code, it automatically generates the CSS code as shown below.

style.css

a {
font-size: 30px;
color: blue;
}
h1 {
font-weight: 300;
color: black;
}
body {
padding-top: 50px;
text-align: center;
background: #d5d5f6;
font-family: 'calibri light';
}

After making all the required changes, run the html file in a browser, so that the following output gets displayed.

Summary

  • Less scope deals with variables and mixins in Less.
  • Both the parent, local scope variables and mixins are searched by compilers.


  • Make sure that both the HTML and LESS files are created in the same node js folder.
  • Check all the required changes in the coding before running the application.