Elevating Your CSS Game with SASS and NPM.

·

10 min read

Blog do Matheus Castiglioni | Dando Poderes Ao Css Com Sass Parte 01

SOURCE

I've seen Sass a couple of times, but I wasn’t really sure what it was all about. My curiosity started building up from constantly seeing it being listed in job ads, and I wanted to know if it was really that much of a big deal. And guess what? After learning about it, I have become a big fan of Sass and all it can do, and I can’t wait to share my knowledge with you.

This article is for people who don't know much about Sass or have only heard of it but don't know how to use it. I will explain the basics and help you write your first Sass code. By the end, I hope to convince you to give Sass a try.

I will be using codepen in the article to help you try out Sass and make it easier for you to follow along.

Let's get started.

What is Sass?

SASS is a CSS preprocessor. It is an acronym for Syntactically Awesome Style Sheets, an extension of CSS that adds elegance, power and more capabilities to the language.

The importance of Sass to every developer working with CSS cannot be overemphasized because it improves the process of writing CSS code by making the code readable, structured, maintainable, reusable and more efficient.

Overall, SASS can improve the quality and efficiency of CSS development, making it an important tool in the web development toolkit.

There are two options for writing the SASS syntax; both are outlined below:

A. The SASS syntax: This is indentation sensitive and does not use any semicolons. Although this method is available, it is not widely adopted.


 .myWriteup
     Color: #fff
     display: block
 & p
     display: inline

B. The SCSS syntax: This stands for Sass CSS and is the most widely used SASS syntax. It preserves how the original CSS is written, making it easy to use.


.myWriteup{
    color: #fff;
    display: block;
& p{
    display: inline;
}
}

The two ways to write sass code have been mentioned above, but in this article, we will focus on SCSS syntax since it is the most popular. But, if you prefer the Sass syntax, you can use it, as there is no difference in functionality between the two.

Note: There are several CSS preprocessors like Less, Stylus, PostCSS, Myth and Rework; however, Sass remains the most popular and widely used CSS preprocessor.

What are the Features of SASS - how do they work?

Sass is designed to simplify the CSS development process, and its features help make this happen. In this section, I will be discussing these features.

For demonstration purposes, I will mainly be using Codepen. To use Sass on Codepen, go to the settings, select CSS, choose the SCSS preprocessor, and save your changes.

  1. Variables: The Sass variable is the same as what a variable means across all programming languages. It is simply a storage location that holds a value. This way, the value stored can easily be changed or updated without a need to go to every point of use to make a change. These can be values representing font-size, color, spacing and almost any property that can take on a value. What variable does is make code flexible and reusable.

    To declare a Sass variable, you start with the dollar ($) sign. Below are examples of how to create a variable in SASS:

     $color-primary: #f9ed69; 
     $width-button: 150px;
     $button-height: 100px;
    
  2. Nesting: One of my favourite features of Sass is its ability to nest selectors within each other rather than writing each selector individually. This reduces the amount of code needed to be written, making it more efficient and easier to maintain. This feature greatly simplifies the process of writing CSS code, and I am sure you will come to appreciate it as well.

    Note: The "&" symbol is used to represent the parent selector in nested rules. It allows you to concatenate the parent selector with the current selector, eliminating the need to repeat the parent selector. The use of the "&" symbol makes nested rules more concise and easier to read.

    To understand nesting, let's compare these two examples doing the same things:

    a . SCSS:

    %[codepen.io/Vickyabiodun/pen/poZGqXy?editors..

    b. CSS:

    %[codepen.io/Vickyabiodun/pen/yLqZZMb?editors..

    When you compare the two codes, you can see how short the SCSS code is because of the nesting feature.

  3. Operations: Sass operation allows you to manipulate values in a way that would not be possible using plain CSS by carrying out mathematical calculations on values. These can be color, height, width or any properties.

    Using this feature, you can carry out standard programming calculations like addition, subtraction, multiplication, division, and modulo on CSS code.

    For example:

      $width: 100px;
      $height: 200px;
    
      .button {
        width: $width + 20px;
        height: $height - 50px;
      }
    

    SASS also supports color operations, such as:

    • Mixing two colours together: mix(yellow, red)

    • Adjusting the lightness of a color: lighten(pink, 20%)

    • Adjusting the darkness of a color: darken(black, 20%)

  4. Partials and Imports: A partial in SASS refers to a file that holds styles and is meant to be included in other SASS files. It is named using an underscore at the start of the filename, such as _navbar.scss, to indicate that it is only meant to be imported, not compiled into a standalone CSS file. The process of importing a partial into another SASS file is straightforward. The @import command is used.

    Simply put, this feature allows you to write CSS in different files and import them all into one file.For example, we have three partials: variables.scss, header.scss, and footer.scss. The variables.scss file defines two color variables that can be used throughout the project. The header.scss, and footer.scss files define styles for a website's header and footer sections.

     // _variables.scss
     $primary-color: blue;
     $secondary-color: green;
    
     // _header.scss
     .header {
       background-color: $primary-color;
       height: 100px;
     }
    
     // _footer.scss
     .footer {
       background-color: $secondary-color;
       height: 50px;
     }
    
     // main.scss
     @import 'variables';
     @import 'header';
     @import 'footer';
    

    Finally, in the main.scss file, we import the variables and both partials using @import. When main.scss is compiled, the resulting CSS file will include the styles from all three partials, and the variables will be accessible throughout the stylesheet.

  5. Mixins: They are simply reusable blocks of CSS codes. They help to eliminate repetitions while writing codes. It is common that a lot of times, we write the same lines of code repeatedly, which can be burdensome. Rather, using mixins allow you to group styles that are used in multiple places and makes it easy to update them in one place.

    Mixins can contain any valid CSS code and can be called using the syntax @include Mixin_name or @include Mixin_name(parameters), passing any necessary arguments to the mixin. When a mixin is included, the CSS code inside it is duplicated in the output CSS.

    There are two ways of writing mixins, just like functions; both methods are described below:

    a. Mixins without parameters:

    @mixin clearfix{

    &::after{

    content: "";

    clear: both;

    display: table;

    }

    }

    //To use nav

    {

    @include clearfix;

    }

    b. Mixins with parameters:

    @mixin style-link-text($color){

    text-decoration: none;

    text-transform: uppercase;

    color: $color;

    }

    //To use

    a:link{

    @include style-link-text($color-text-dark);

    }

  6. Functions: The Sass function is similar to mixins, but unlike mixins which are used to include styles in a ruleset, they return a value. Functions are useful for abstracting complex calculations, making your SASS code more reusable and easier to maintain. We can write our function or use the SASS inbuilt function, although we will rarely have to write our own functions.

    • Self-written function:

      @function divide($a,$b){

      @return $a/$b;

      }

      //To use

      nav{

      margin: divide(60,2)* 1px;

      background-color: $color-primary;

      @include clearfix;

      }

    • In-built: There are several inbuilt functions, e.g. lighten and darken.

      .btn{

      &:hover{

      background-color:darken($color-secondary, 15%);

      }

      } .main_file{

      &:hover{

      background-color:lighten( $color-tetiary, 10%);

      } }

Important to know - Placeholders:

Placeholders are blocks of CSS code that are intended to be reused elsewhere in your stylesheet but are not output on their own. Placeholders are defined using the % symbol and are included in other rulesets using @extend.

For you to understand this better, when we use mixins, the code is copied into the selector, but with a placeholder, the selector is used to replace the placeholder.

In conclusion, mixins allow you to duplicate and reuse code, while placeholders allow you to inherit and extend code, keeping your CSS output small and efficient.

I will use codepen to demo; click on the setting to view the compiled CSS code so that you can see the compiled result. This will help you understand better.

%[codepen.io/Vickyabiodun/embed/YzjRXoZ?edito..

Now that you know the basics of Sass and that it needs a compiler, you may be wondering if your browser can serve as the compiler. The answer is No. Sass requires a separate compiler to convert its code into standard CSS. Don't worry; I will cover all the details in the article. Keep reading!

Installing SASS and using it in your local project.

There are multiple ways to install Sass on your computer, but the simplest method, which I will be discussing, is through NPM packages.

To get started, you'll need to create separate files/folders for your CSS and Sass code. After that, you can link your CSS file to your HTML just like you normally would. Then, we'll use npm to compile the Sass code into CSS.

What is NPM?

NPM is an acronym for Node Package Manager. It is the default package manager for Node.js. Also, npm makes it easy to install, update, and manage different libraries and tools while also managing dependencies between packages, ensuring that your projects use compatible versions of the packages they depend on. Npm contains so many packages; SASS is just one.

To begin using npm, follow these steps:

  • Download Node Installer

  • Go to your command line or terminal, then cd folder you are working with.

  • Type npm init - This will help create the package.json file.

  • Type npm install node-sass –save -dev. By writing this, you will install node-sass and save it as a development dependency in your package.json file.

Following these steps, you can easily share your project without sharing the entire node module. So if someone else receives or clones your project, they just need to type “npm install” and all the dependencies will automatically be installed.

  • Compile your sass script: To do this, you edit the script's location in the JSON file and follow the command as seen below. The “-w” stands for watch, which means it should allow the changes in your code to be monitored and implemented.

    Note: While your project is running, don’t close the terminal. If you need to do other stuff, open another tab.

    Bonus point - How to automatically reload your page when any change occurs using npm.

    To automatically reload changes using npm, you can open a new tab in your command line or terminal. The goal is to install the page globally and not locally.

    • Go to your command line or terminal; type “npm install live-server -g”. The “-g” stands for global, which makes it a global installation and can work for all your projects with no exception. I use a mac, so while installing, I ran into an error cause of permission stuff. So if you run into an error too, what you have to do is enter “sudo”, then it will ask for your password, and the installation can go on fine.

Conclusion

In this article, we've learned about Sass and how it can improve our CSS development process by making the code more readable, structured, maintainable, reusable, and efficient. We've also learned how to install Sass using npm and the difference between scss and sass syntax. Also, we've explored some of the key features of Sass, including functions, nesting selectors, mixins and using the & sign to represent the parent selector.

By now, you're equipped with the basic knowledge of Sass, but it's just the tip of the iceberg. There's a whole world of features and possibilities that Sass has to offer, and I encourage you to keep exploring and finding new ways to streamline your CSS development knowledge. Don't be afraid to experiment and try out new things. You never know; you might discover a whole new world of possibilities.

I hope this article has been informative and helpful in your journey to learning Sass.

To learn more about SASS, visit.

If you have any questions or feedback, feel free to reach out to me. I'd be more than happy to help you out.

Happy coding!