fbpx
SASS The Ultimate Guide for modern day web development

SASS: The Ultimate Guide for modern day web development

As the life of CSS has developed, it has become seen increasingly important to have more control over organization as well as a better workflow than what is currently offered by the stylesheet language. This need has been filled by CSS preprocessors such as LESS, PostCSS, and arguably the most popular, Sass. In this post, we will take a look at what preprocessors are, why they can have such a positive impact on your CSS workflow, and how you can get started using Sass.

What is a CSS preprocessor?

A CSS preprocessor is essentially a scripting language that will turn CSS code with minor syntax variations into regular CSS3. In the case of Sass, this is a script that has originally been written in Ruby, although there are ports available using other languages such as JavaScript, via Node.js.

How to get started with Sass

There are many different options for using Sass. On the command line, there are the options of using the original Ruby gem, the Node.js port, or using task runners such as Gulp or Grunt. If you’d prefer to use a GUI, several recommendations include Compass, CodeKit, or Hammer.

What all of these programs do is take the Sass code from one stylesheet (a .sass or .scss file), and then compile it into a regular .css file. There are pros and cons to each options, but if you are uncertain of where to get started, one of the GUI programs would be a good place to start.

Variables

One of the most useful features of Sass is the ability to create variables. Just like any other proper programming language, you can assign values to variables to recall any time you use it. Variables in Sass are written with a $ sign before the name, for example:

$mainColor: #dbcbb4;

This is useful for at least two reasons: 1. Any time you want to re-use the same color or other value, you simply need to re-use the variable, never having to remember common styles. 2. If you ever need to change the value for multiple selectors, all you have to do is change the one value in the variable.

Nesting

Another useful feature of Sass is the ability to nest declarations into each other. This can be useful to show how different declarations relate to each other. As an example, instead of having to write:

.container {
    width: 800px;
}
.container h1 {
    font-size: 40px;
}

You can simply write:

.container {
    width: 800px;
    h1 {
      font-size: 40px;
    }
}

Functions

Sass has many built-in functions, which allow for actual manipulation of CSS code. Here are just a few examples:

Mix two colors together:

mix($primarycolor, $secondcolor)

Make a color darker (where $amount is a value of how much to darken it by):

darken($color, $amount)

Math

Another handy feature is the ability to apply math expressions to your markup. You can use all of the operators typically supported in programming languages: addition, subtraction, division, multiplication, modulo, equality and inequality.

One thing to note is that you can’t mix value units. So while the following is valid:

$menu-height: 100% - 20%;

The following would not be possible:

$menu-height: 100% - 40px;

Some common use cases of Sass

Some common use cases of Sass

In an earlier post, we covered getting set up with Sass and being able to convert your files to standard CSS. In this post we’ll cover some of the most common techniques for getting the most out of Sass — making a variety of style rules significantly easier to write.

Mixins

With varying levels of browser support for different CSS properties, it’s common to have to provide different vendor prefixes to properties, in order to ensure cross-browser compatibility (especially when support for Internet Explorer is necessary):

p {
  -webkit-transform: scale(2); 
      -ms-transform: scale(2);
          transform: scale(2);
}

 

This can be a pain to have to do repeatedly for each property with varying levels of support. Using a Sass Mixin can simplify the process whenever having to repeat large sections of code.

Using the code for the transform property above as an example, we can easily turn this into a reusable mixin whenever we want to use a transform: scale() rule:

@mixin transform-scale($x) {
    -webkit-transform: scale($x);
        -ms-transform: scale($x);
            transform: scale($x);
}

 

With the mixin above, we define the amount we want to scale each transform with the $x argument. This mixin can then be used in any Sass code block, by using the @include statement beforehand:

p {
    @include transform-scale(2);
}

 

For Loops

Similar to programming languages such as JavaScript, PHP or Python, Sass allows you to create a for loop, to iterate over a defined number of times. Defined using the @for keyword, the length of Sass for loops can be indicated in two different ways: “x through y” or “x to y”, where x is the starting point and y is the end point. When defining the loop with through, the loop will include the end value (so for example, 1 through 10 would include 10 in the loop), whereas using to would have the loop go up to but not including the end value (i.e. 1 to 10 would only go from 1 to 9). As an example of using 1 through 10:

@for $i from 1 through 10 {
    .col-#{$i} { width: 100% / 10 * $i; }
}

 

The @for loop above would apply a width calculation to 10 different CSS classes (each starting with .col- followed by a number between 1 and 10). The loop would set a width for each CSS class, defined by 100% / 10 multiplied by the classes number (1 through 10). This would result in the following rule sets for each of the classes:

.col-1 {
    width: 10%;   
}
.col-2 {
    width: 20%;
}
.col-3 {
    width: 30%;
}
.col-4 {
    width: 40%;
}

...

.col-10 {
    width: 100%;
}

 

This is a quick and easy way to define columns in a basic grid structure.

Partials

When working with Sass, it’s often a good idea to organize your code into reusable sections or files based on the type of styles they apply (for example, having a file for your grid layout, another file for mixins, another for color schemes, etc.). Sass encourages this modular workflow by using what is referred to as partials. A partial would be any Sass file that begins with an underscore (_), for example _grid.scss. You can then have a directory of all of your partials, then one main Sass file to import these into, such as main.scss.

To import these partials into your main file, you would simply use an @import statement at the top of the file:

// main.scss file

@import 'grid'
@import 'mixins'

 

When working with partials, you don’t need to supply the underscore or filename extension. Sass will automatically detect these. This makes it easy to use partials to better organize your code.

 How to use node-sass to compile Sass files in an npm script

how to compile the popular Sass preprocessor into regular CSS

While there are numerous options for choosing how to compile the popular Sass preprocessor into regular CSS, a compiler that utilizes the LibSass engine has increasingly become more common. Initially written in Ruby, using the original Ruby gem or a Ruby-based program such as Compass to compile Sass quickly became host to a variety of criticisms regarding its slow compiling time and overall speed. In answer to the performance complaints, the original Sass engine was ported over to C/C++ as LibSass, with numerous wrappers available to run the Sass engine in just about every popular programming language. This tutorial will introduce the Sass programming language and also provide a step-by-step guide to using the node-sass wrapper to compile your Sass code, directly as an npm script. Note that node-sass is intended to be used with .scss files rather than .sass, the former being the more common and popular option.

About Sass CSS Preprocessor

Sass, or Syntactically Awesome Style Sheets, is an example of a CSS preprocessor, which enables responsive web developers to create code in one language and then “translate” it into CSS. Licensed under MIT, Sass boasts its compatibility with CSS and highly feature-rich programming language, making it a perfect combination of the characteristics of a stylesheet and a computer program. In this sense, it is a powerful tool for website developers who are familiar with programming, although anyone can learn how to operate Sass with enough practice. Also, there are two slight variations of the Sass language, the Sassy CSS (abbreviated as SCSS) and simply Sass. While Sassy CSS is much more similar to CSS in terms of syntax, Sass is a better preference for app developers who are more concerned about convenience. The latter option omits curly brackets and semicolons and instead reads code based on indentations.

It is important to note that most developers and online documentation sources will use SCSS syntax because of its similarity to CSS. In addition, you should note that web browsers do not read Sass or SCSS files. Therefore, you must convert all SCSS/Sass files into CSS before publishing your website onto the Internet. For an explanation on how to do this, please refer to “Converting between SCSS to CSS files” below.

Setting Up Sass

Install Node.js and NPM

If you don’t already have Node.js installed, you can download the latest version on its official site. If you are not familiar with this term, Node.js is a popular runtime environment for Javascript. Node comes pre-packaged with npm, the official Node package manager which gives developers access to open source Javascript code, so it will be installed at the same time. (If you are interested or need to install npm separately, you may do at the official website for npm.) To check that npm was installed successfully, run npm -v in your terminal to confirm the version of npm currently on your computer. At the time this blog post was updated, the latest version of npm released is 6.7.0.

Install node-sass

Once you have npm installed, it’s time to install node-sass. You can do so by running npm install -g node-sass in your terminal to install the package globally (i.e. available across your entire system), or run npm install node-sass without the -g flag to only install to your current directory.

Project setup with package.json

Assuming node-sass is now installed globally, it’s time to make or choose a project directory where we want to watch our Sass files. Navigate to your project directory, and initialize the project with a package.json file, by running npm init.

Setting Up Sass

You’ll be prompted to input a variety of details on the project, such as package name, version, description and other details. You can either fill in this info now or just hit Enter for each of these prompts and fill it in later.

Install Node.js and NPM

After cycling through each of the prompts, there will be a prompt to confirm the entered info (or info left blank). Hit enter once more and the package.json file will be created.

Install node-sass

Add the node-sass script

Open the package.json file in your text editor of choice, and add the following line inside the "scripts" object:

"scss": "node-sass --watch assets/scss -o assets/css"

The line above tells npm to run a script, watching for changes to any .scss files in the assets/scss directory and commit those changes to corresponding CSS files in a assets/css directory. You should change the paths for your directories accordingly.

Your edited package.json file should look something like this:

{
  "name": "sass-ex",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "scss": "node-sass" --watch assets/scss -o assets/css"
  },
  "author": "",
  "license": "ISC"
}

 

Save the file and close it. Now in the root of the project directory, run npm run scss to start watching for any changes to your .scss files.

Alternative Ways of Installing Sass

It is important to note that there are various alternative methods of installing Sass. For instance, you can install Sass via paid and free applications such as CodeKit and Scout-App. In addition, you can also install Sass by downloading the package from the official Github site and adding it directly to your path.

Overview of Designing with Sass

As mentioned previously, Sass comes with many beneficial features that make it a powerful tool for website developers. Sass adopted these traits from basic programming language, some of which this blog post will discuss below. For a more thorough guide of these features and how to implement them in your code, visit the official guide on the Sass website.

Variables

Just like in programming, you can create and implement variables in Sass throughout your style sheet. This is extremely convenient because if there is a certain style you want to use throughout your website (for example, a type of font package, color, etc.), you can simply store it in a variable and use it throughout your stylesheet. Declaring a variable in Sass is especially straightforward for programmers because it is conceptually identical to Javascript. For instance, if you declare $primary-color: #525; ($variable: value;) at the beginning of your stylesheet, then you can simply input $primary-color for any color value.

Nesting

HTML and most popular programming languages maintain a clean structure with the use of indentations or nesting. On the other hand, a traditional CSS stylesheet is rather one lengthy, cluttered list of various styles. But with Sass, you can enhance the readability of your stylesheets by placing different blocks of code within other code. For instance, inside of the styling of a traditional nav bar, you can nest the code for designing the placement of the list items and the style of the text. This visual hierarchy of code through nesting is another reason that many developers will gravitate towards the use of Sass in their websites.

Importing SASS files

As your websites and the HTML documents become more complex, this will typically result in a parallel growth of your CSS files. However, creating more styles will eventually clutter your stylesheets, making it difficult to maintain and write in an orderly fashion. Fortunately, by using Sass, you can divide up your stylesheets into multiple Sass files. When you are ready to launch your website, you can combine the multiple SCSS files into one master stylesheet, and then link this to your HTML document through the importing feature. Unlike CSS, it will only require one HTTP request to load the single Sass “master” stylesheet; in CSS, the client makes an HTTP request for each stylesheet imported. To import a stylesheet, simply write keyword @import followed by the name of the sub-stylesheet in quotation marks (@import “stylesheet”;). This is another key feature of Sass that simplifies the process of managing a website.

Using Mixins

Most people with programming experience are familiar with writing functions or methods in their programs; however, traditional CSS files do not support this feature. Fortunately, Sass allows developers to write mixins, or a group of CSS declarations that are grouped together and can be used repetitively anywhere on your stylesheet. A mixin is essentially the equivalent to a function; it can accept an input value and plug it into the CSS declarations grouped inside the mixin. To create a mixin, simply write @mixin mixinName(value) followed by the CSS declarations that use the inputted value. To call on this mixin in your stylesheet, write keyword @include followed by the mixin’s name and value (if applicable). Mixins in Sass undoubtedly pave the way for powerful and efficient website design by creating less repetitive code.

Sass allows developers to write mixins, or a group of CSS declarations

Using Inheritance and Other Directives

Another powerful programming feature that you can implement through website development with Sass is inheritance. You can refer to this as “extending” selectors in Sass. With the use of @extend, selectors can inherit the CSS properties of other selectors, thus simplifying your code immensely by removing the need for repetitive code. This creates more flexibility in your stylesheet by only “turning on” a selector with the keyword @extend. To use this feature, simply create a selector with the % symbol in front to indicate that the CSS properties in this selector can be extended. Now, when you are creating another selector, you can call @extend %selectorName; and its properties will be inherited by that new selector.

While the @extend function is wildly popular among Sass advocates, there are many basic programming functions that have been integrated into the Sass language. For instance, most programmers are familiar with the use of conditional statements. Now, Sass developers can use @if and @else directives which will lead to much more powerful website development. Similarly, those who are familiar with the traditional for and while loops can replicate these Java functions with the @for and @while directives.

Using Operators

Programmers use mathematically driven algorithms all of the time. On the other hand, there is practically no usage of math involved in traditional CSS design. Luckily, Sass allows developers to use basic operators (+, -, *, /, %) to calculate pixel or percentage values in CSS declarations. It is a small but highly practical tool for designers who wish to create more complex websites. According to the official documentation for Sass, there is also a library of math-driven functions that Sass developers can use. Actually, most programmers are probably familiar with many of these functions in the library. It includes functions such as abs($number) to find absolute value, min($numbers…) to find the smallest of multiple values, and random() to return a random numerical value. To view all of the functions available on Sass, visit the official documentation site for Sass.

Converting between SCSS to CSS files

After you have finished designing your HTML elements using Sass, it is time to finally publish your website. However, you cannot directly use the SCSS files when loading your website. Instead, you must convert your files to CSS. With the Sass gem, which can be installed through the command line, there a variety of executables available. If you do not have the Sass gem installed, you may also run the Sass executables with another source.

  • sass or $ bundle exec sass: Used to convert a source Sass file into a CSS file. Run sass --help for more for more instructions.
  • sass-convert or $ bundle exec sass-convert: Used to convert between Sass, SCSS, and CSS files. Run sass-convert --help for more instructions. This is a perfect executable for existing projects that you would like to switch over to SCSS format.

Converting between SCSS to CSS files

Other CSS Preprocessors

Stylus

Stylus is another highly popular alternative for a CSS preprocessorModeled after Sass, Stylus is another highly popular alternative for a CSS preprocessor. A particularly useful feature that draws many users towards Stylus is its highly dynamic and flexible language and syntax. Users have the option of omitting punctuation such as curly braces, colons, and semicolons. They can even omit certain keywords (for example, @mixin) if they prefer. Similar to Sass, Stylus integrates many powerful programming features such as functions/mixins, variables, iteration, and inheritance. A particularly useful feature in Stylus is the CSS literal, indicated by @css. This keyword can be used to revert back to CSS type if Stylus is unable to accommodate a request.

Less

Less, which stands for Leaner Stylesheets, is another CSS preprocessorLess, which stands for Leaner Stylesheets, is another CSS preprocessor option that is very similar to its alternatives. It offers many built-in programming features. This includes creating variables, using mixins, nesting your code, and utilizing a library of built-in functions. Unlike Stylus, Less is more strict in its syntax. In fact, it practically replicates the syntax of traditional CSS code. Based on your personal preferences, you may view this as an advantage or a disadvantage.

 

SASS Versus LESS

SASS Versus LESS We need to go through a few basics to understand what SASS and LESS are. So let us start by discussing the CSS preprocessor. A CSS preprocess is a scripting language that programmers use to extend CSS when they write code in one language. The CSS preprocessor then compiles it into CSS. SASS is the most popular example of this CSS preprocessor while others like LESS and Stylus are lesser-known.

What is SASS?

SASS stands for Synthetically Awesome Style Sheets which allows users to add several things like variables, inline imports, nested rules, etc to their code. SASS also helps users keep things organized through the coding process which makes it easier to handle these sheets. SASS works with all versions of CSS but owners need to have Ruby installed in their system for it.

SCSS

Similarly, SCSS is a special file type in Ruby that assembles CSS Style Sheets for a browser. So, you can say that SCSS is like CSS but with better formatting for coding.

What is LESS?

LESS stands for Learner Style Sheets and is a backward compatible language extension that people use in CSS. It is fairly easy to learn LESS because it looks just like CSS. You can use LESS to nest rules inside of rules because of which the rules apply within the outer rule selector.

This allows developers and designers to add their own CSS rules according to the DOM structure in a document. These nested rules make it easier to understand and follow when executing a code.

LESS or SAAS: What Should I Use?

It is quite difficult to understand whether LESS is better than SAAS or vice versa but we can compare their features to get a clearer idea of which one users should opt for. Let us do a comparative analysis of SASS and LESS to get a better idea of which one is better?

SASS and LESS both use similar functions and mixins. However, SASS uses Ruby as a base language. On the other hand, LESS uses JavaScript for coding. The difference in coding language still does not give an edge to any of these languages.

LESS lets the users use the Mixins under certain conditions only. While this sounds like a helpful feature, it also explains the logical link limit in LESS. SASS, provides a different approach. For example, SASS allows users to utilize loops and case-oriented distinctions during the programming.

SASS gives users the freedom to use SCSS or an indented syntax, which gives them the freedom to abide by the CSS rules or deviate from them. However, the code in LESS is automatically a superset of CSS. SASS is more popular among the development community but not just because of its feature, but because it is an older language.

Which is better SASS or SCSS or LESS?

Let us take a look at the individual characteristics for SASS, SCSS, and LESS, to see which of these CSS extensions are better for developers.

SASS

  • SASS helps reduce the repetition in CSS to save time and is an extension of CSS. It is a superset of CSS that is coded in the Ruby language
  • SASS has its syntax and compiles it into CSS in a readable form
  • SASS can report errors in syntax
  • Allows users to create their functions and use them in the user’s context.
  • SASS uses mixing to create styles that you can use and reuse
  • SASS focuses more on the knowledge base, thus, it does not have visuals

LESS

  • LESS helps users maintain, customize, manage and handle style sheets for websites. It is a dynamic language and works on several browsers.
  • Developed on JavaScript which makes it a superset of CSS used to reduce redundancy
  • Explains accurate errors as well as the location of the errors
  • Helps manipulate values through JavaScript, which can change colors, round functions, ceil functions, etc.
  • LESS also uses Mixens.
  • LESS provides documentations with appealing visuals with easy to follow steps.

SCSS

  • SCSS is a special type of fie for SASS that allows additional functionality in CSS.
  • SCSS does not require a syntax code
  • SCSS does not need to follow strict indentions, unlike SASSS
  • SCSS resembles SASS in writing styles but the use of brackets and semicolons is necessary
  • It has a file extension
  • SCSS has a smaller developer community as compared to SASS, which is why the support with SCSS is lower too.

Does Bootstrap Use SASS OR LESS?

Does Bootstrap Use SASS OR LESS Bootstrap is a popular choice for the development community globally, and since LESS was such an influence on the market during Boostrap 3, it offered a SASS alternative. However, things change entirely when you consider Boostrap 4. It is because Boostrap 4 uses SASS entirely. This is the first time that Boostrap’s source code uses SAAS.

Therefore, it is safe to say that SASS is a safer consideration for the future. Experts believe that Boostrap made this bold move because the number of SASS users are nearly double compared to LESS users.

Why Are More Developers Using LESS and SASS Instead Of CSS?

Recent market trends reveal that more developers are now using LESS and SASS instead of CSS for various reasons. For instance, any project that starts, requires only a few rules of CSS but then the rules get complicated as the project advances. This makes CSS difficult to learn and adapt to for more advanced projects. Therefore, people like going for options like LESS and SASS that have production-ready features available.

Similarly, development via CSS is time-consuming and increases the average time required to complete a task. Other languages like JavaScript hold regular conferences to communicate about advancements, but there is no such thing in CSS. All of these things make LESS and SASS a much better alternative than CSS.

That said, it is clear that both SASS and LESS play vital roles in the world of development. SASS is still popular despite coming to the industry earlier than LESS. Both these extensions have their merits and demerits and it all depends on how the users utilize them.

Conclusion

All in all, Sass is a great tool for website developers who are looking to enhance their web design with basic programming functions. Not only is installation straightforward, but the Sass language and syntax is quick to learn.

The various programming functions, such as mixins and variables, and the visual hierarchy of Sass create more efficient and maintainable stylesheets.

I hope that this article will guide you as you experiment with the cutting-edge technologies outlined above.

angelo frisina sunlight media

Author Bio

Angelo Frisina is a highly experienced author and digital marketing expert with over two decades of experience in the field. He specializes in web design, app development, SEO, and blockchain technologies.

Angelo’s extensive knowledge of these areas has led to the creation of several numerous award winning websites and mobile applications, as well as the implementation of effective digital marketing strategies for a wide range of clients.

Angelo is also a respected consultant, sharing his insights and expertise through various podcasts and online digital marketing resources.

With a passion for staying up-to-date with the latest trends and developments in the digital world, Angelo is a valuable asset to any organization looking to stay ahead in the digital landscape.

3 Comments

  • Garrett Corwin February 15, 2019 at 3:08 pm

    I’ve done this and many varieties of this with no luck. Terminal always throws the same error: missing script:scss. I have a feeling it’s because I’m using node-sass 4.11.0 and there have been changes since most of these guides came out. Any thoughts? Thanks

  • Jordan April 15, 2019 at 2:39 pm

    This is because there is a typo in setting up the script. There should not be a quotation mark after node-sass. So, instead of “scss”: “node-sass” –watch assets/scss -o assets/css”, the line should read
    “scss”: “node-sass –watch assets/scss -o assets/css”

  • Angelo Frisina January 28, 2020 at 10:51 pm

    Thanks for bringing this to our attention Jordan.