In this chapter Less Mixins as a Function, one can learn about Less Scope, Less mixins and its uses.
Description
Mixins can also act as functions. The defined variables and mixins are visible and can be used in caller’s scope. The variable is not copied, when the caller contains a variable with the same name, this was the only exception in mixins.
The variable present in the caller's local scope is protected, whereas, the variable of parent scope is overridden.
Example
Below example explains the mixin to put a border only on the top of div.
Conceptual
figure
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.
Step 1
Create a simple HTML file in Nodejs folder as shown below.
Mixins_functions.html
[c]
<div>
<h1>Welcome to <strong>SPLessons</strong></h1>
<h3>Less Mixins are awesome<h3>
</div>
[/c]
Step 2
Create a Less file in the same node js folder as shown below.
style.less
[c]
div {
.border-top-radius(125px);
background: rgb(255, 255, 255);
display: inline-block;
padding: 50px;
}
.border-top-radius(@radius) {
border-top-right-radius: @radius;
border-top-left-radius: @radius;
}
// Ignore, is for demo
body {
padding-top: 50px;
text-align: center;
background: rgb(244, 244, 244);
font-family: 'Lato';
}
h1 {
color: rgb(250, 88, 130);
font-weight: 300;
}
h3{
color: rgb(110, 110, 110);
font-weight: 200;
}
[/c]
Step 3
Compile the above Less file in command prompt using the command.
[c]lessc style.less style.css[/c]
Step 4
By compiling the Less file, it automatically generates the css file as shown below.
style.css
[c]
div {
border-top-right-radius: 125px;
border-top-left-radius: 125px;
background: #ffffff;
display: inline-block;
padding: 50px;
}
body {
padding-top: 50px;
text-align: center;
background: #f4f4f4;
font-family: 'Lato';
}
h1 {
color: #fa5882;
font-weight: 300;
}
h3 {
color: #6e6e6e;
font-weight: 200;
}
[/c]
Result
After making all the required changes, you need to run the html file in a browser to get the following output.
Summary
Key Points
The main drawback of less mixins is: variables with same names remain same and are not copied.
Less mixins override parent scope variable and protect local scope variables.
Programming
Tips
Make sure that both the files are created in the same node js folder.
Check all the required changes in the code like font size, color, etc. before running the application.