Less CSS - SPLessons

Chapter 11

Less Operations

Less Operations

In this chapter, one can learn about Less Operations, its uses and how to use Numbers, Colors, and Variables in Less.

The basic math operation can be performed for the following data types.
Less supports some arithmetic operations such as (+) plus, (-) minus, (*) multiplication and (/) division. By using Less operation, one can save lot of time when working on variables.

Below is the basic snippet code of Less operations.

/* Number */

h1 {
margin-bottom: 15px - 10px;
margin-bottom: 15px - 10;
}

/* Color */

h1 {
color: #888888 / 4;
}

/* Variable */

@h1-default-margin-bottom:  25px;
h1.tight {
margin-bottom: @h1-default-margin-bottom - 15px
}

Below example explains the use of Less operations.
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 Nodejs folder as shown below.

Less_operations.html

<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 operations are awesome</p>
</body>
</html>

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

style.less

@fontSize: 30px;

h1 {
color: rgb(75, 75, 200);
font-weight: 300;
}

body {
text-align: center;
}

.myclass {
font-size: @fontSize - 10;
color:gray;
}

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

lessc style.less style.css

By compiling the code, it automatically generates the following CSS code.

style.css


h1 {
color: #4b4bc8;
font-weight: 300;
}

body {
text-align: center;
}

.myclass {
font-size: 20px;
color: gray;
}

After making all the required changes, one needs to run the html file in a browser to get the following output.

Summary

  • Less operations save a lot of time for developers who work on variables.
  • The code gets minified using basic math operations defined by variables.


  • Make sure that both the HTML and LESS 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.