The Power of CSS Processors in Web Applications Development

Codica Team
Codica Journal
Published in
7 min readDec 11, 2019

Pre- and post-processors are popular front-end development tools. When it comes to clean and readable code, they become especially useful. Sass, Less, and Stylus are the most widely used pre-processors. In its turn, PostCSS is the first post-processor worth mentioning.

Today, we will show how you can simplify your code and become more productive with the help of pre- and post-processors.

Sass: CSS with superpowers

For starters, let’s define what Sass means. The exact explanation we can find on the official website of this CSS extension.

“Sass is a stylesheet language that’s compiled to CSS. It allows you to use variables, nested rules, mixins, functions, and more, all with a fully CSS-compatible syntax. Sass helps keep large stylesheets well-organized and makes it easy to share design within and across projects”.

Now let’s discuss loops and map functions. These interesting and rare tools help us seize all the power of CSS.

What do we know about SCSS? It is an extension of CSS syntax. At Codica, we use it for developing web projects for a good reason. Since it is closer to native CSS, there is no need to perform extra operations when you copy your code from a browser.

The code snippet below showing the process of Web Fonts declaration in CSS is a perfect example of code duplication in style sheets.

@font-face {
font-family: ‘OpenSans-Light’;
src: url(‘opensans-light.eot’);
src: url(‘opensans-light.eot?#iefix’) format(‘embedded-opentype’),
url(‘opensans-light.woff2’) format(‘woff2’),
url(‘opensans-light.woff’) format(‘woff’),
url(‘opensans-light.ttf’) format(‘truetype’),
url(‘opensans-light.svg’) format(‘svg’);
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: ‘OpenSans-Regular’;
src: url(‘opensans-regular.eot’);
src: url(‘opensans-regular.eot?#iefix’) format(‘embedded-opentype’),
url(‘opensans-regular.woff2’) format(‘woff2’),
url(‘opensans-regular.woff’) format(‘woff’),
url(‘opensans-regular.ttf’) format(‘truetype’),
url(‘opensans-regular.svg’) format(‘svg’);
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: ‘OpenSans-Bold’;
src: url(‘opensans-bold.eot’);
src: url(‘opensans-bold.eot?#iefix’) format(‘embedded-opentype’),
url(‘opensans-bold.woff2’) format(‘woff2’),
url(‘opensans-bold.woff’) format(‘woff’),
url(‘opensans-bold.ttf’) format(‘truetype’),
url(‘opensans-bold.svg’) format(‘svg’);
font-weight: normal;
font-style: normal;
}

One look at this code snippet gives us a sense of dealing with the code repetition.

The fans of the Matrix blockbuster will remember the scene when Neo sees a black cat walking by and then another one behaving the same way. This moment was a clear illustration of déjà vu during the Hotel Ambush.

So how can we fix code duplication issues? The answer is with the help of Sass components called map functions and mixins.

The example below shows how these instruments can help you simplify your code.

First things first, we will describe our fonts in map fonts. This process looks the following way:

/* Fonts map format
$fonts: (
$file-name: ‘$font-name’
)
*/
$fonts: (
opensans-light: ‘OpenSans-Light’,
opensans-regular: ‘OpenSans-Regular’,
opensans-bold: ‘OpenSans-Bold’,
);

Next off, we will use map-get function for declaring variables font:

$ff_light: map-get($fonts, opensans-light);
$ff_regular: map-get($fonts, opensans-regular);
$ff_bold: map-get($fonts, opensans-bold);

With the feature @mixin we can steer clear from the code repetition:

@mixin font-face($font-name, $file-name) {
/* ‘/assets/fonts/’ — relative path to the fonts folder */
$filepath: ‘../assets/fonts/’ + $file-name;
@font-face {
font-family: #{$font-name};
src: url($filepath+’.eot’);
src: url($filepath+’.eot?#iefix’) format(‘embedded-opentype’),
url($filepath+’.woff2') format(‘woff2’),
url($filepath+’.woff’) format(‘woff’),
url($filepath+’.ttf’) format(‘truetype’),
url($filepath+’.svg’) format(‘svg’);
font-weight: normal;
font-style: normal;
}
}

After that iterator @each and @mixin mentioned above will help you declare font-face for each font:

/* Font face declaring */
@each $file-name, $font-name in $fonts {
@include font-face($font-name, $file-name);
}

Now if you want to add or delete a new font, you need to upload or delete font files lying in the path which was previously declared in variable $filepath (‘../assets/fonts/’ in the example). Don’t forget to follow file naming, declared in map $fonts and declare or delete variable:

$fonts: (
opensans-light: ‘OpenSans-Light’,
opensans-regular: ‘OpenSans-Regular’,
opensans-semibold: ‘OpenSans-Semibold’,
opensans-bold: ‘OpenSans-Bold’,
);
$ff_light: map-get($fonts, opensans-light);
$ff_regular: map-get($fonts, opensans-regular);
$ff_semibold: map-get($fonts, opensans-semibold);
$ff_bold: map-get($fonts, opensans-bold);

Now it becomes clear what features and tools make CSS the core part of your project stylization.

When it comes to pre-processors, including Sass, their power lies in the ability to help front-end developers write clean and efficient code that can be easily supported. Easy maintenance, in its turn, serves as the most basic requirement for complex web projects.

PostCSS: A tool for transforming CSS with JavaScript

Pre-processors are not the only tools for styling web projects. Let’s not forget about post-processors that had become a crucial aspect of CSS workflow. For example, PostCSS is a software development tool used to transform CSS styles with JavaScript plugins.

The usage of Preset Env which is CSS plugin and CSS Modules is optional. The plugin is responsible for making modern CSS compatible with most browsers. The main task of CSS Modules is to fix the issue of the so-called global scope relevant to CSS.

At the same time, we cannot imagine a complicated web project without code linting and adding vendor prefixes to support cross-browser compatibility.

Why use Post-processors in web applications development?

Benefits

Post-processors speed up the web app development process, make the code more readable and solve issues related to cross-browser compatibility. If you need to add support for some properties, use @mixin to add prefixes to them. In this example, we add mixins to the transition property which makes it possible for us to declare reusable styles without code duplication:

@mixin transition($args…) {
-webkit-transition: $args;
-moz-transition: $args;
-ms-transition: $args;
-o-transition: $args;
transition: $args;
}

Drawbacks

However, this approach is not flawless. It adds prefixes to all browsers even if Internet surfers don’t use them.

Luckily there is PostCSS with plugin Autoprefixer to save the day. This plugin automatically adds prefixes browsers in CSS. The results are avoided code duplication, reduced number of manual operations and time saved.

Let’s take a closer look at Autoprefixer and other plugins.

PostCSS plugins and tools

Autoprefixer

GitHub offers the following description of Autoprefixer:

“PostCSS plugin to parse CSS and add vendor prefixes to CSS rules using values from Can I Use. It is recommended by Google and used in Twitter and Alibaba.”

The developers also focus on the fact that “Autoprefixer uses Browserslist, so you can specify the browsers you want to target in your project with queries like > 5%”.

This is a partial solution to the cross-browser compatibility issue. We rely on global statistics that differs depending on the region.

Let’s see what Autoprefixer developers mention in this regard on GitHub:

“If you want to change the default set of browsers we recommend to combine last 1 version, not dead with > 0.2% (or > 1% in the US, > 1% in my stats). last n versions adds too many dead browsers and does not add popular old versions. Choosing a percentage above 0.2% will, in the long run, make popular browsers even more popular. We might run into a monopoly and stagnation situation, as we had with Internet Explorer 6. Please use this setting with caution.

Opera Mini has 100 million users in Africa and it is more popular in the global market than Microsoft Edge. Chinese QQ Browsers has more market share than Firefox and desktop Safari combined.”

Browserslist

ideally, we should fix on an end-user. Browserslist offers us this possibility due to Browserslist-ga. This package gathers statistics from Google Analytics and keeps it in the JSON file which is used in Browserslist.

There’s a detailed guide on how to use this tool on the Browserlist-ga page:

“In the root directory of your project run:

npx browserslist-ga

Npx comes with npm 5.2+, for older versions run:

npm install -g browserslist-ga

and then:

browserslist-ga

To run the latest code directly from GitHub, execute instead:

npxgithub:browserslist/browserslist-ga

You will be asked to log in with your Google Account. Your access token will only be used locally to generate a browserslist-stats.json file in the root of your project. After finishing the steps, you can use your stats with Browserlist by adding the following to your Browserslist config:

> 0.5% in my stats # Or a different percentage

Note that you can query against your custom usage data while also querying against global or regional data. For example, the query

> 1% in my stats, > 5% in the US, 10%

is permitted”.

At long last, we have “clean” CSS with browser support, based on the statistics of visits to our site.

As it is stated on Browserlist-ga page:

“All the praise goes to the humans and Martians that develop and maintain Can I Use and Browserslist”.

CSSNext

CSSNext is a PostCSS plugin that allows using the latest CSS syntax. For instance, you can use new custom properties without bothering about browser support.

Stylelint

Finally, there is Stylelint. It is a CSS linter for proofreading and validating the CSS code. With its help, you can avoid errors and follow consistent coding conventions.

Conclusion

CSS pre- and post-processors gain traction for a good reason. They simplify web application development workflow, as a result, increasing productivity, and enable front-end developers to write clean code.

Our guide was aimed at showing you how we use CSS Processors to develop custom software products of any complexity. We hope these examples from our practice demonstrate all the power of the mentioned tools.

The article was originally published on Codica Blog.

--

--

Codica Team
Codica Journal

Software development consultancy. We are passionate about innovations and create great online marketplaces with Ruby on Rails, React, Vue and Angular.