CSS Preprocessors: An Overview Of The Best CSS Preprocessors With Examples.
CSS preprocessors can be programs that help you generate CSS from the preprocessor's unique syntax. Most of the time, when creating a website, we style its various elements using CSS Preprocessors. When creating a website, CSS is a necessity for every developer. Although we can style our web page directly in HTML, CSS keeps our work and code much more organized. You can customize your website or web page elements using many features and properties with CSS.
While many CSS options are available, these preprocessors may add features that aren't present in pure CSS. Nesting, mixing, inheritance, and many other features fall under this category. These extra features serve the sole purpose of making the CSS structure much more thorough and straightforward to maintain. As a result, many developers opt for either one of the many CSS preprocessors available.
The Best CSS Preprocessors
Below are some of the best CSS preprocessors;
- Sass
- LESS
- Stylus
Sass (Syntactically Awesome Style Sheet)
Being first made available in 2006, Sass is the oldest CSS preprocessor. It was inspired by the Haml templating language, which gave HTML dynamic features and was developed by Natalie Weizenbaum and Hampton Catlin. They wanted CSS to have comparable dynamic functionality as well. As a result, they created a CSS preprocessor and gave it the name Syntactically Awesome Style Sheets. Using variables, if/else clauses, for/while/each loop, inheritance, and other computational logic in their CSS code is made possible by Sass. Frontend developers.
Sass was initially discouraged from being used by many developers because it was written in Ruby and required Ruby to compile the code. However, the LibSass library's release significantly increased the use of Sass. With the help of the C/C++ library LibSass, we can parse Sass and other backend languages like Node, PHP, and even C.
There are two syntaxes for Sass. The code does not include semicolons and curly brackets when using the older, indentation-based syntax associated with files ending in .sass. The newer and more popular syntax is associated with files ending in .scss. It employs semicolons and braces in the typical CSS Preprocessors syntax.
A simple example of Sass/SCSS syntax is shown below. Only two variables, $primary-color, and $primary-bg, are declared in the code and applied to the HTML element body. The more recent SCSS syntax is fully compliant with the traditional CSS syntax, whereas the older Sass syntax is easier to write and more error-prone.
Example Snippet
/* SCSS */ $primary-color: seashell; $primary-bg: darkslategrey; body { color: $primary-color; background: $primary-bg; } The same code with the Sass syntax: /* Sass */ $primary-color: seashell $primary-bg: darkslategrey body color: $primary-color background: $primary-bg Both compiles to the same CSS: /* Compiled CSS */ body { color:seashell; background: darkslategrey; }
Features
In Sass, storing values we want to reuse throughout the code in variables is possible. The $ sign is prefixed to variables in Sass, as shown in the example above. The scope of Sass variables allows us to use them locally and globally, giving them a lot of flexibility.
To prevent duplication, Sass adheres to the DRY (Don't Repeat Yourself) programming principle. Mixins and the @extend rule are two of its features that enable DRY implementation.
The use of mixins enables the quick application of a large number of related CSS rules to any property. The following mixin, for instance, uses the parameters width, height, background, and border to create a straightforward card layout.
/* SCSS */ @mixin card($width, $height, $bg, $border) { width: $width; height: $height; background: $bg; border: $border; } With the @include rule, we pass four arguments to the card mixin whenever we create a new card: /* SCSS */ .card-1 { @include card(300px, 200px, blue, green 2px solid); } .card-2 { @include card(400px, 300px, lightgreen, black 1px dotted); }
A smaller card with a blue background and a green border and a larger card with a light green background and a black dot border is produced by these two calls:
/* Compiled CSS */ .card-1 { width: 300px; height: 200px; background: blue; border: green 2px solid; padding: 20px; } .card-2 { width: 400px; height: 300px; background: lightgreen; border: black 1px dotted; padding: 20px; }
The Sass language now supports inheritance thanks to the @extend rule. Having various design components that share certain traits is incredibly helpful. The @extend rule allows us to add any class's properties to another class in the manner described below:
/* SCSS */ .class-1 { width: 100%; height: auto; } .class-2 { @extend .class-1; }
As Sass supports nesting, the @extend rule extends all nested selectors. The language's powerful nesting feature greatly enhances the readability and maintainability of code. When we have selectors with the same parent, it can be applied, for example:
/* SCSS */ article { p { line-height: 1.5; } img { max-width: 100%; }
With so many options, our CSS can accommodate quite complex logic. The most adored features of Sass are its loops and conditionals, which let us write CSS rules just like in any scripting language. With the help of Sass's built-in if() function, @if directive, @for, @each, and @while loops, we can test various conditions and repeatedly output particular sets of styles.
We want to use the partial Sass files that contain smaller code blocks repeatedly, such as a _reset.scss stylesheet, allow us to use Sass to support modularity as well. The @import rule allows partials to be added to any other Sass file.
We can also apply other dynamic functionalities to our design using the built-in functions of the Sass preprocessor, such as changing and combining colors, manipulating strings, and performing mathematical calculations. We can also define our unique Sass functions, just in case that isn't enough.
Tools & Examples
Sass has a fantastic ecosystem, including a vibrant developer community, a wide variety of tools, and libraries. Sass has gained additional traction because both the most popular frontend frameworks, Bootstrap and Zurb
Foundation, are written.
Additionally, Sass has strong mixin libraries and authoring frameworks like Compass and Bourbon that improve the language's functionality even more. Several well-known businesses use Sass in their production websites, including Airbnb, Kickstarter, Hubspot, Zapier, Freshbooks, and many others.
LESS (Leaner Style Sheets)
The newer SCSS syntax was motivated by the syntax of LESS, which is an exciting way in which later LESS also influenced Sass. Three years after Sass, in 2009, Alexis Sellier published LESS for the first time. Many of its features, including mixins, variables, and nesting, are implemented because Sass influenced it.
The LESS CSS preprocessor extends the CSS language's built-in functionality through a JavaScript library. We require Node.js to install and run the LESS compiler because it is written in JavaScript. However, by including .less files and the LESS converter in the head> section of our HTML page, we can also compile LESS instantly using the .less file extension; LESS uses the standard CSS syntax.
Therefore, a valid .css file is also a valid .less file. Therefore, even though LESS has a few extra elements you won't find in CSS, like the @ sign for variables, it's straightforward to learn the syntax if you already know CSS. LESS has excellent documentation where you can find everything related to its syntax and detailed examples.
As an illustration, the same sample code that we examined in the Sass section above would appear as follows in LESS:
/* LESS */ @primary-color: seashell; @primary-bg: darkslategrey; body { color: @primary-color; background: @primary-bg; } Naturally, it compiles to the same CSS: /* Compiled CSS */ body { color: seashell; background: darkslategrey; }
Features
In the same way, Sass variables have scopes, LESS variables also have scopes that make them accessible where they are called and defined. Furthermore, they can be utilized in CSS rules and selector and property names, URLs, and @import statements. When necessary, we can access frequently used URL paths by storing them in variables, for example:
/* LESS */ @uploads: “../wp-content/uploads/”; header { background-image: url(“@{uploads}/2018/03/bg-image.jpg); } This compiles to the following background rule: /* Compiled CSS */ header { background-image: url("../wp-content/uploads/2018/03/bg-image.jpg"); }
/* LESS */ @uploads: “../wp-content/uploads/”; header { background-image: url(“@{uploads}/2018/03/bg-image.jpg); } This compiles to the following background rule: /* Compiled CSS */ header { background-image: url("../wp-content/uploads/2018/03/bg-image.jpg"); }
We can use the @uploads variable from the abovementioned example multiple times without worrying about the URL path.
LESS mixins allow us to reuse a group of related style rules throughout the code, much like Sass mixins. Additionally, LESS provides us with particular guarded mixins that implement rudimentary conditional logic. As an illustration, the two distinct font colors (black and white) defined in the following code example are applied based on how light the background is. (The example uses the lightness() LESS function as well.)
/* LESS */ .text-color (@bg-color) when (lightness(@bg-color) >= 50%) { color: black; } .text-color (@bg-color) when (lightness(@bg-color) < 50%) { color: white; } .text-color (@bg-color) { background-color: @bg-color; } .card-1 { .text-color (blue); } .card-2 { .text-color (red); }
Black fonts are used on the first card with the blue (light) background and white fonts are used on the second card with the red (dark) background thanks to the guarded mixin .text-color in the compiled CSS:
/* Compiled CSS */ .card-1 { color: black; background-color: blue; } .card-2 { color: white; background-color: red; }
Even though LESS lacks Sass' more sophisticated conditional logic (such as an if-else statement), mixin guards still allow us to accomplish much. Additionally, starting with version 1.5.0, we can use mixin guards just like when we use the when keyword on CSS declarations. Here is a straightforward example from the docs:
/* LESS */ button when (@my-option = true) { color: white; }
Additionally, LESS offers us several built-in tools to work with colors, images, gradients, dimensions, units, and other attributes.
The LESS programming language incorporates inheritance and the DRY principle because we can extend selectors with the :extend pseudo-class and combine values from multiple properties with the :merge feature. Nesting is also supported by LESS, making it simple to create a readable and understandable code base.
Tools & examples
The popularity of LESS suffered greatly due to Bootstrap's decision to switch Bootstrap 4 from LESS to Sass, even though it still has a LESS distribution. Other LESS frameworks include Cardinal and Semantic UI, which has a LESS-only version.
However, Compass for Sass is less potent. LESS has a few mixin libraries available, like LESS Hat. It's worth looking at the excellent curated list of LESS tools on Github, which goes by the name of Awesome LESS. On production websites like WeChat, Patreon, Nordstrom, the Royal Opera House, Indiegogo, Transferwise many others, we can also run into LESS.
Stylus
One year after LESS, in 2010, former Node.js developer TJ Holowaychuk released the first version of Stylus. To make it simple for developers to incorporate Stylus into their Node projects, it is written in Node.js. LESS and Sass both had an impact on it. Sass's potent logical capabilities are combined with LESS's straightforward setup in Stylus.
Developers frequently praise Stylus for its concise and adaptable syntax. We have a variety of ways to write code with Stylus, which uses the .styl file extension. Although we can use the typical CSS syntax, we can also omit brackets, colons, and semicolons, or we can completely omit punctuation. Using the various Stylus syntaxes, for instance, our previous code example appears as follows:
/* Stylus standard CSS syntax */ primary-color = blue; primary-bg = darkslategrey; body { color: primary-color; background: primary-bg; } However, we can remove the brackets: /* Stylus syntax without brackets */ primary-color = blue; primary-bg = darkslategrey; body color: primary-color; background: primary-bg; The brackets and the semicolons can be removed: /* Stylus syntax without brackets and semicolons */ primary-color = blue primary-bg = darkslategrey body color: primary-color background: primary-bg All punctuation (brackets, semicolons, colons) can be removed: /* Stylus syntax without punctuation */ primary-color = seashell primary-bg = darkslategrey body color primary-color background primary-bg
However, since the assignment operator (=) denotes the declaration of a new variable, we are unable to remove it. Since Stylus is a pythonic (indentation-based) language, proper indentation must always be observed, or the code will not be compiled.
Features
Stylus has similar basic features as Sass and LESS. Variables have an obvious syntax. We need to pay attention to the equal sign; without even prepending them:
/* Stylus */
primary-color = blue
Like Sass and LESS mixins, stylus mixins let us save and reuse individual style rule sets. However, Stylus is the only program that supports transparent mixins. They enable us to automatically add vendor prefixes to more recent attributes with limited browser support. For the experimental user-select property, for example, we may construct a transparent mixin and reuse it as many times as we like:
/* Stylus */
user-select(n)
-WebKit-user-select: n
-Moz-user-select: n
-ms-user-select: n
user-select: n
div
user-select(none)
Only the user-select transparent mixin to a CSS selector (div) is needed; assign a value to it (none), and Stylus produces all the vendor prefix rules that are necessary:
/* Compiled CSS */
div {
-WebKit-user-select: none;
-Moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
If you routinely create @keyframe animations, Stylus may be your perfect CSS preprocessor, as it automatically inserts vendor prefixes to keyframes.
Stylus has several built-in tools that may be used to adjust and change colors and unit types, compute average, minimum, and maximum values, match patterns and carry out other tasks. For instance, the grayscale() Stylus function allows us to get the grayscale equivalent of any color rapidly:
/* Stylus */
grayscale(royalblue)
With Stylus, we can create robust custom functions, much as with Sass.
Similar to Sass, Stylus also gives us access to solid conditional logic. It has a conditional statement with an if/else/else if and an unless/else if. The unless statement is the opposite of it, we can also think of it as an "if not" statement. Additionally, we may employ postfix conditionals and for/in looping with Stylus.
There are also more sophisticated capabilities in Stylus that developers routinely laud, like partial reference and property lookup, which provide access to just a limited number of levels of nested selectors and the ability to reference past properties without assigning them to variables.
Tools & Examples
There are some excellent Stylus frameworks, including Basis and Kouto Swiss, despite their lack of popularity compared to Foundations or Bootstrap. A few mixin libraries for Stylus, including Nib and Ride.css, give developers access to pre-made cross-browser Stylus mixins. The most well-known Stylus corporate users include Livestorm, Accenture, Zenchef, HackerEarth, and Coursera.
Conclusion
The functions of variables, mixins, importing, and nesting are shared by all CSS preprocessors. They may execute conditional statements, functions, and operations adhering to the DRY concept. Before picking one over the other, we must consider a few key distinctions in their advanced features.
Sass and Stylus are more like programming languages since we can create new functions and have sophisticated logical and looping capabilities.
However, Sass has a sizable ecosystem and a vibrant community and is also utilized by well-known frontend frameworks. Stylus, on the other hand, is very versatile and is simple to integrate into Node projects. LESS is also suitable for serverless architecture since it can be quickly constructed on the frontend and has excellent built-in functions while having less logic-based capabilities than Sass and Stylus.
To learn more about CSS, visit our CSS Tutorial Page.