What is a CSS preprocessor? Get started with LESS (Linear Style Sheet)

CSS is generally used with HTML to style web pages. But CSS is primitive and incomplete as it’s very hard to achieve in CSS to build a function, reuse a definition or inheritance and many more. To achieve these properties, CSS preprocessors come into the picture.

Prerequisites:

We are considering that you have a good understanding of CSS properties and react js components to continue with this blog.

Getting Started:

The CSS preprocessors are scripting languages that extend CSS  with variables, operators, conditions, functions, mixins and many more other usable properties and then we compile that scripted language to our regular CSS. SASS, LESS and Stylus are the well-known CSS preprocessors.

CSS preprocessors help us to write reusable and maintainable CSS code. 

Popular CSS Preprocessors:

There are currently three of the most popular and stable CSS preprocessors SASS, LESS and Stylus but there are many others as well. All CSS preprocessors accomplish similar tasks, but they do so in a slightly different manner and with different syntax.

Each CSS preprocessor has its own syntax that they compile into regular CSS. And also every one of them has its own feature and ecosystem (framework or library).

Get started with LESS:

LESS stands for (Linear Style Sheet). It was initially released in 2009 and it is influenced by Sass, therefore it implements many of its features, including mixins, variables, and nesting.

LESS uses the standard CSS syntax with the .less file extension. This means that a valid .css file is also a valid .less file. Therefore, it’s really easy to learn LESS if you know CSS, even if there are a few extra elements that are not found in CSS.

Features:

Following are some of the important features of LESS:

Variables:

The variables are used to provide reusability. We use @ sign for creating the variables in LESS.

//Variables

 @color : green;

 @table_height : 400px;

 @table_width : 700px;

 We can also perform calculations while creating the variables.

//Arithmetical operations +, -, *, / in less

@table_height: 400px;

@table_width: @table_height + 300px//result 700px

@min_height: @table_height - 100px//result 300px
@max_height : @table_height * 2//result 800px

@head_color : #224488 / 2; //results #112244

Parent Selector:

The parent selector lets us access the parent (root) element.

@heading_color: green;


.heading {
 color: @heading_color;
 &:hover {
   color: red;
 }
}

Mixins:

Mixins allow us to embed all the properties of a class into another class. It behaves like a function and also takes the arguments.

//mixins
.flex-property(@justify-property, @bordersize:0px, @borderstyle:solid, @bordercolor:white ) {
 display: flex;
 flex-direction: row;
 flex-wrap: wrap;
 justify-content: @justify-property;
 border: @bordersize @borderstyle @bordercolor;
}

In upper code, we have created mixin which has flex property. We can also pass parameters exactly the same as parameters we pass in functions. 

let’s see how we can use this mixin.

#nav-item {
 ul {
   .flex-property(space-between); //here we have used mixin and also have passed the argument.

   padding: 0px;
   margin: 0px;
   margin-top: 10px;
   text-align: center;
   li {
     display: inline-block;
     color: @light-color;
     font-size: 20px;
     text-decoration: underline;
   }
 }
}

Recursion:

We can call mixin inside the mixin which creates recursion. Below we have shown how exactly it works.

.generate-columns (4);
.generate-columns (@n, @i: 1) when (@i =< @n) {
 .column-@{i} {
   width: (@i * 100% / @n);
   .generate-columns (@n, (@i + 1));;
 }
}

After compilation to CSS.

.column-1 {
 width: 25%;
}
.column-2 {
 width: 50%;
}
.column-3 {
 width: 75%;
}
.column-4 {
 width: 100%;
}

Mixin guard:

Mixin guard is useful when we want to put some style on the basis of an expression. let’s see its example.

.mixin (@a) when (lightness(@a) >= 50%) {
 font-size: 24px;
}
.mixin (@a) when (lightness(@a) < 50%) {
 font-size: 20px;
}
.mixin (@a) {
 color: @a;
}
.class1 {
 .mixin(hsl(120, 50%, 80%));
}
.class2 {
 .mixin(hsl(120, 50%, 40%));
}

//After compilation
.class1 {
 font-size: 24px;
 color: #b3e6b3;
}
.class2 {
 font-size: 20px;
 color: #339933;
}

In the above example, we are applying different font sizes to class1 and class2 based on the lightness of the color which is applied to both of the classes.

Merge:

The merge property is used to extend the multiple properties into a single property. We can use this property in two ways either through coma (,) or space merge. For coma, we use the “+” sign after every attribute and for space, we use the “+_” sign.

This property is helpful while applying shadow or transition effect.

//less code
.myfunc () {
 box-shadow+: 5px 5px 5px grey;
}
.class {
 .myfunc();
 box-shadow+: 0 0 5px #f78181;
}

//after compilation
.class{
 Box-shadow: 5px 5px 5px grey, 0 0 5px #f78181;
}


//less code
.mixin() {
 transform +_: skew(10deg, 10deg);
}
.myclass {

.mixin();
 transform+_: rotate(-15deg);
}

//after compilation
.myclass{
 transform: skew(10deg, 10deg) rotate(10deg, 10deg);
}

Nested directives:

With the help of the nested rules of less, we can implement the media query code which is nothing but the nested directives.

.myclass {
 @media screen {
   color: blue;
   @media (min-width: 1024px) {
     color: green; //this will apply when screen width 

                     is >= 1024px
   }
 }
}

Here we have discussed all the features of LESS which are very much used and I believe this is enough to get you started with LESS in your next project. For further reading, you can explore the official documentation of less.

How to use LESS in react js:

If you have created the react project with CRA (create react app) then it’s by default support only saas and CSS.  If we want to use LESS in our react project then either we can run the npm run eject command first and then modify webpack configs or we can also use the concurrently module.

Let’s see how we can use LESS in react project with the help of concurrently module step by step.

1) Create react project:

First of all, we need to create a new react app. Open your terminal create a basic react app with CRA command.

npx create-react-app less-with-react

2) Import all required modules:

We need to import all the required modules. Open your terminal and inside your project run the below command.

npm install less less-watch-compiler concurrently --save-dev

Here we imported less which is obvious and a less-watch compiler which is needed for compiling the LESS file into CSS and concurrently module.

3) Create config file:

Now create a less-watcher.config.json file inside your root directory and set the below configuration.

{ 
    "watchFolder": "src/",
    "outputFolder": "src/",
    "runOnce": false,
    "enableJs": true
 }

Here we can change the “watchFolder” and “outputFolder” src according to our .less file location.

4) Change scripts:

Inside your package.json file replace the start script in package.json with the following.

"scripts"



   "start": "concurrently --kill-others \"less-watch-compiler --config    less-watcher.config.json\" \"react-scripts start\"",

 "build": "react-scripts build"

  .... 

}

And here is done, now we are ready to use the LESS file inside our react project

For the demo, you can refer to the following link

Advantages:

We can write reusable and maintainable code in CSS with the help of the advanced features of Pre-processors. By using a pre-processor, we can easily increase our productivity and decrease the amount of code in the project.

coma

Conclusion

In this article, we discussed the CSS preprocessors, their types and the features of one of the pre-processor LESS. We have also seen how to use Less inside the react application.

Thank you for reading! In case you have any questions feel free to comment.

Nadeem Khan

Frontend Developer

Nadeem is a Front-end developer with 1+ year of experience. He has experience in web technologies like ReactJS, Redux and UI Frameworks. His expertise in building interactive and responsive web applications, creating reusable components and writing efficient, optimized and DRY code. He enjoys learning about new technologies.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks