Thilanka Godakumbara

An introductory guide to CSS preprocessors

If you are interested in developing an HTML structure for a web application, you will want to make it visually appealing for users. Cascading Style Sheets (CSS) are normally used to achieve beautification of web applications. Over the years CSS had a newer version named CSS2, and recently the latest upgrade was released as CSS3.

Speaking of HTML, there are two main categories that HTML stylings branch into. They are as:

  • CSS preprocessors – this has been around for ages (examples are: Sass, Less, Stylus and others)
  • CSS-in-JS libraries – this is a relatively new approach to styling (such as free-style, and etc.)

In this technical article, I will attempt to cover the subject of CSS preprocessors. I am also suggesting you read further and understand both categories – because both have their own pros and cons. Following, you will be able to choose between the two for successful implementation upon your web application.

 

First, let’s take a pass at understanding preprocessors –

A preprocessor can be summarily described as ‘a computer program that modifies data to conform with the input requirements of another program’.

To explain in simpler terms, a preprocessor is a language that takes as input – a text file using a programming language syntax – and outputs another text file that follows the syntaxes of another programming language.

Cascading Style Sheets also possess a technique to speed up web development and allows for the coding of maintainability.

CSS preprocessors are integrated with advanced features that can help you write reusable code, and also will help you make the same code extensible and maintainable. In short, Preprocessors can help to increase developer productivity. There are a few sample preprocessors like Sass, Less, Stylus, Turbine, CSS-Crush, Compass, CSS Cacheer and  DtCSS in trend.

However, Sass (Syntactically Awesome Stylesheet), Less – (Leaner Style Sheets) and Stylus are the more popular preprocessors used in web development.

If you are interested in knowing which one is better and most suitable for your project I recommend you to try the above mentioned three and decide. Some developers may be inclined to work with Sass and some developers with Less or Stylus.

Each one does similar things, but in a different way and with their own syntaxes. But they all possess some advanced unique features.

This technical guide covers the above three main types, namely: Sass, Less and Stylus. We shall compare features of each and their pros and cons

Getting started with Sass, Less and Stylus

 

Sass – “CSS with super powers”

 

Introduction

CSS preprocessors are a result of implementing a language which can add dynamic features to CSS. Accordingly, it is named as Syntactically Awesome Stylesheet (Sass). It was released in 2006 and Sass is the oldest, most maturest, most stable and most professional extension of CSS and adds power and elegance to the basic language.

Sass is written in Ruby and it also needs Ruby to compile the code. Due to limitations such as Sass being solely reliant on Ruby to compile, LibSass was introduced.

LibSass is a library which is a C/C++ port of the Sass engine to help developers integrate Sass with most of the available backend languages such as Node, PHP and C. To learn more about LibSass click here.

 

Syntax

There are two syntaxes used in Sass, they are .sass and .scss extensions.

.sass is the oldest and is known as indented syntax and provides a more concise way of  writing css. It uses indentations and omits semicolons and curly brackets.

The newer and more widely used syntax is .scss extension. It uses the standards css syntax with braces and semicolons.

 

(Code snippet 1 : Sample code featuring .sass extension)

 

(Code snippet 2 : Sample code featuring .scss extension)

 

And the output will be the following CSS code

(Code snippet 3 :Output CSS code)

 

Less – It’s CSS, with just a little more
Introduction

Three years after Sass was introduced, Less was released. It was influenced by Sass, therefore many features in Sass are also available in Less. Less is a backward-compatible language extension in CSS. Less is compiled to CSS by a javascript library. Node.js needs to be installed and then run the Less compiler. Thus, Less is capable of running on both client and server sides.

Less allows for real time compilation with less.js by the browser when compared to other CSS preprocessors.

>npm install -g less

And create style.less file for implementations.

Syntax

Less is using standard .less extension.

(Code snippet 4 :Sample code featuring .less extension)

 

Compiled CSS as follows.

(Code snippet 5 : Compiled CSS)

 

Stylus – “Expressive, Dynamic and Robust CSS”
Introduction

The first version of Stylus was launched one year after Less was launched. Stylus is written in Node.js so that developers can easily integrate it into their Node projects. It was influenced by both Sass and Less. Stylus combines the powerful logical abilities of Sass with the easy and straightforward setup of Less.

>npm install stylus -g

It is cross-platform too and can be written in both JavaScript and Node.js. With stylus you can define your own set of functions for CSS parameter management and expansion.

Another major advantage of Stylus are the transparent mixins. This helps you to define the functions, but without the need to specify the list of parameters. It helps you copy any parameter string into the CSS.

Here are some advantages of stylus:

  • Powerful logical functionality
  • Ability to run via Node.js / JavaScript, (no Ruby)
  • Ability to run as part of the Node.js setup (use Grunt and Bower)
  • Clean and minimal flexible syntax
  • A general smoothness in the way Stylus approaches its various features.
Syntax

Stylus uses .styl  file extension and it allows you to write code in different ways. We can use standard CSS syntax and we may also omit brackets ,colons, and semicolons.

 

(Code snippet 6 : Sample code featuring .styl extension)

 

We can omit and use above brackets , semicolons and colons. The compiled css will be as follows (see code snippet 7)

(Code snippet 7 : Compiled CSS)

 

Features

Above all preprocessors possess some interesting common features that can help make styling with CSS easier. A few of them are:

  • Variables
  • Operations
  • Mixins
  • Nesting
  • Functions
  • Interpolation
  • File importing
  • Extends

 

Variables: you can define a variable by prefacing a word with $(Sass) or @(Less) and assigning it a value. Note that variables can only be defined once, so be careful when choosing names. Also, using functional naming conventions versus style naming conventions can be useful as well. Variables must be declared first in the file, so that it loads first and the CSS that comes after it can reference it. There are two things you should be aware of when using variables.

Name by function – Do not name your variables using the same value name. Name it by the function it does. Following examples using Scss:

(Code snippet 8 : Name a variable by function)

 

Consistent Indentation – If you have a set of variables it is better to indent them by group. Following example using Less:

(Code snippet 9 : Consistent indentation using Less)

These defined variables can be used in styling.

(Code snippet 10 :Using defined variables in styling)

 

Operations: Doing math operations in CSS is quite useful and is also fully possible. It is simple and this is how to do it:

(Code snippet 11 : Preprocessors can handle mathematical operations too)

 

Mixins: Mixins are functions that allows developers to reuse properties throughout a stylesheet. Rather than having to go through a stylesheet and change a property multiple times, we can now simply change it inside our mixin. This can be very useful for specific stylings of elements and vendor prefixes. When mixins are called from within a CSS selector, the mixin arguments are recognised and the styles inside the mixin are applied to the selector.

Example using Scss:

(Code snippet 12a : using a mixin function)

Output:

(Code snippet 12b : output following a mixin function)

 

Example using Less:

(Code snippet 13a : Example CSS code using Less)

Output:

(Code snippet 13b : Less output)

 

Nesting:  Nesting allows styles to be grouped more clearly in the precompiled CSS file.

(Code snippet 14a :using the  Nesting function)

 

Output:

(Code snippet 14 b: Compiled output)

Functions: The Mixins example already looks like a function. There is, however, the ability to do some powerful stuff with calculating values. For example, the lighten function takes a color value and a percentage and will adjust the lightness of that value.

(Code snippet 15 a : Using functions to lighten a color)

 

Output:

(Code snippet 15 b: Function output)

 

Here are some functions that used in stylus and Sass ( we can use these functions with Less by using specific syntaxes).

 

Stylus Sass
red(color)


green(color)


blue(color)


alpha(color)


dark(color)


light(color)


hue(color)


saturation(color)


lightness(color)

saturate($color, $amount)


desaturate($color, $amount)


lighten($color, $amount)


darken($color, $amount)


adjust-hue($color, $amount)


opacify($color, $amount)


transparentize($color, $amount)


 mix($color1, $color2[, $amount])


 grayscale($color)


 complement($color)

 

Interpolation:
  • Variable Interpolation
Less Scss Stylus
@var: color;

.class-@{var} {

 @{var}: #ed3d66;

 background-@{var}: #ed3d66;

 content: @var;

}

$var: color;

.class-#{$var} {

 #{$var}: #ed3d66;

 background-#{$var}: #ed3d66;

 content: $var;

}

$var = color

.class-{$var}

 {$var}: #ed3d66

 background-{$var}: #ed3d66

 content: $var

Output:  

.class-color {

 color: #ed3d66;

 background-color: #ed3d66;

 content: color;

}

 

  • Interpolation with Calc()
Less Scss Stylus
@var: 5px;

div {

 height: ~”calc(7em + @{var})”;

}

$var: 5px;

div {

 height: calc(7em + #{$var});

}

$var = 5px

div

 height: “calc(7em + %s)” % $var

Output:

div {

 height: calc(7em + 5px);

} 

 

  • Selectors Interpolation
Less Scss Stylus
@headings: h1, .h1, h2, .h2, h3, .h3;

@{headings} {

 font-family: “Great Custom Font”, sans-serif;

}

$headings: “h1, .h1, h2, .h2, h3, .h3”;

#{$headings} {

 font-family: “Great Custom Font”, sans-serif;

}

$headings = h1, .h1, h2, .h2, h3, .h3

{$headings}

 font-family: “Great Custom Font”, sans-serif

Output:

h1, .h1, h2, .h2, h3, .h3 {

 font-family: “Great Custom Font”, sans-serif;

}  

 

  • Nested Selectors interpolation

If you often find yourself extending selectors with the same pseudo selectors and/or modifier classes, then you may use a variable similar to the example above when nesting – although  this won’t work in Less.

 

Scss Stylus
$active: “&.is-active, &:hover”;

.selector {

 foo: bar;

 #{$active} {

baz: qux;

 }

}

$active = “&.is-active, &:hover”

.selector

 foo: bar

 {$active}

baz: qux

Output:

.selector {

 foo: bar;

}

.selector.is-active,

.selector:hover {

 baz: qux;

}

File importing: This feature is only available in Less which references imports. A normal import will grab the contents of that file and dump it into the file asking for it which is super useful. Concatenating files is a vitally important feature of preprocessors. A (reference) import doesn’t do that. In fact, it doesn’t put anything at all into the file asking for it. The code in that file is just now ready to use, either by calling a mixin within it or extending a selector within it.

That’s a pretty powerful concept. It means you could import an entire library but just use the bits and pieces you want.

 

Extends:

Extends help you share generic definition with selectors, instead of copying. While using Less, you can either select only the main instance or you can use every instance of extended selectors by adding the “all” attribute to extend method. In Sass, it is different. It extends all instances of extended selectors including its child selectors and inherited properties.

 

 

Code snippet 16 – Less


Code snippet 17 – Scss


Code snippet 18 – Stylus

 

Conclusion

All CSS preprocessors have similar functionalities as we discussed in this article. They all follow DRY principle and perform conditional statements, functions and operations.

Sass and Stylus are more like programming languages as they have advanced logical and looping abilities and allow to write custom functions.

Less possesses fewer logic based features compared to  Sass and Stylus. It can be easily compiled on the frontend.

Thank you for reading our latest Mitra Innovation blog post. We hope you found the lessons that we learned from our own startup story interesting, and you will continue to visit us for more articles in the field of computer sciences. To read more about our work please feel free to visit our blog.

 

References and suggested further reading:

Thilanka Godakumbara

Senior Software Engineer | Mitra Innovation