Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

What Less is

Less is a CSS preprocessor: a program that reads styles written in an extended language and turns them into plain CSS. You write variables, nested rules and mixins, and the browser receives finished rules without them. This conversion is called compilation.

The course uses Less 4 (versions 4.x), the current major version. The compiler is written in JavaScript and is installed as the npm package less.

From Less to CSS

Here is a small Less file. It keeps the brand colour in a variable and nests the hover state inside the button rule:

// styles/main.less
@primary: #2563eb;
 
.btn {
  padding: 8px 16px;
  color: white;
  background: @primary;
 
  &:hover {
    background: black;
  }
}

What the browser gets after compilation:

.btn {
  padding: 8px 16px;
  color: white;
  background: #2563eb;
}
.btn:hover {
  background: black;
}

The variable is gone — its value was put in its place, and the nested rule became a separate .btn:hover rule. The result works in any browser:

<style>
  .btn {
    padding: 8px 16px;
    color: white;
    background: #2563eb;
  }
  .btn:hover {
    background: black;
  }
</style>
 
<button class="btn">Sign up</button>

Hover over the button — the background turns black.

Less and Sass

Less and Sass solve the same problem and look alike. The main differences in syntax:

LessSass (SCSS)
Variable@primary$primary
Mixinan ordinary class or .name()@mixin and @include
Conditionswhen guards@if and @else
Loopsrecursive mixins, each()@each, @for, @while
CompilerJavaScript (less)Dart (sass)

Any valid CSS is also valid Less, so you can rename style.css to style.less and add features gradually.

Where Less is used today

New projects more often choose Sass or plain CSS with custom properties. But Less is still around:

  • Bootstrap 3 — its sources are written in Less, and many sites still run on it;
  • Ant Design up to version 4 — themes were customised with Less variables;
  • Magento 2 — online shop themes are built from Less;
  • Semantic UI and Fomantic UI — their themes are Less too;
  • older company projects and admin panels.

So it is worth being able to read and maintain Less, and the end of the course shows how to move it to Sass or plain CSS.

Common mistake

The browser does not understand Less. Linking the source file does nothing:

<link rel="stylesheet" href="styles/main.less">
<p>The styles were not applied.</p>

Always link the compiled .css file. The next lesson shows how to get it.

Thanks for reading!

Donate to the site — we work hard for you.