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.
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
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.
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 is a front-end developer with 1.5+ years of experience. He has experience in web technologies like React.js, 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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork