The Absolute Beginner's Guide to Sass

The Absolute Beginner's Guide to Sass

 
 

You've probably heard about CSS preprocessors before, whether it's Sass, LESS or Stylus, and they're all great tools to maintain your CSS, especially when you work with large codebases. For "lay" (;-)) people:

A CSS preprocessor is a program that allows you to generate CSS from the unique syntax of the preprocessor. There are many CSS preprocessors to choose from, but most CSS preprocessors add certain features that do not exist in pure CSS, such as mixin, nesting selector, inheritance selector, etc. These features make the structure of the CSS easier to read and maintain.

The next natural step is to use a preprocessor when you have mastered CSS. The main advantage is that you don't have to repeat yourself. In other words, your CSS is Dry.

It also includes clean code, variables, and component reuse. It's easy to maintain and organize. You can save a lot of time!

In this article, we'll concentrate on Sass. The most popular preprocessor in use today. We are going to dive into Sass, how to compile Sass into a regular CSS, and we're going to look at some of the features that make it so powerful.

What is Sass?

In short, Sass is a CSS preprocessor that adds special features like variables, nested rules and mixins( sometimes called syntactic sugar) to the regular CSS. The aim is to facilitate and make the coding process more efficient. Let's go into more detail.

SCSS or Sass?

There are two ways to write in Sass— SCSS, and Sass— but after they have been compiled they generate similar output.

  • The modern standard is SCSS (aka Sassy CSS). It's a very similar syntax to CSS because it uses brackets and semi-colons. In this syntax, even normal CSS is valid. The extension of the file is.scss
  • . Sass is an older syntax focusing on indenting separate blocks of code and newline characters into separate rules. It has the.sass file extension.

We will use SCSS in this article because it is the most natural syntax. It is also very useful when you convert regular CSS to SCSS because you can just paste and work from there!

How to install Sass

First, before we can write a Sass code, it will be locally installed. We are now starting the process of setting up the environment to write and compile Sass. Note: When compiled, Sass is converted to a regular CSS code that can be interpreted and rendered by browsers.

Environment setup:

We must have npm installed on our computer before we start, it comes packed with Node.js.

If you're unsure whether or not Node.js has been installed, run node -v from your terminal. It's installed if you see a version number.

Folder Structure:

Let’s create our project folders! They will be structured like so:

my-sass-project
   |- sass
   |- css

To create this structure, open the terminal and change the folder into which you want our sass project to be installed( via cd command). Run the following commands, then:

mkdir my-sass-project
cd my-sass-project
mkdir -p sass css

File Structure:

We will need an index.html and main.scss, of course. Run:

touch index.html
cd sass
touch main.scss
cd..

 Don’t forget to add <link rel=”stylesheet” href=”css/style.css”> to your index.html.

Initialize our Project Directory:

Every project using npm needs to be initialized. To do this, enter the command below. This creates a .json package for our project.

npm init -y

How to Install node-sass

node-sass is the library which allows us to compile .scss to .css. Run the following command to install node-sass as dev dependency.

npm install node-sass --save-dev

Sass Code to CSS

Next, we need to create an npm script to run the compilation. Add this script inside the script section of our previously created package.json file.

"compile-sass": "node-sass sass/main.scss css/style.css"

Here we specify main.scss as our main Sass file and style.css as the CSS file. Adding a --watch flag to your script is extremely handy. The watch flag tells the compiler to look at the source files for changes and to automatically re-compile to CSS every time you save your Sass files. Add -watch and save the script again:

"compile-sass": "node-sass sass/main.scss css/style.css --watch"

Now the Sass is automatically compiled to CSS every time you save— nice!

Make sure you keep the terminal window running in the background–the script will stop running if you close the terminal. If you have to stop the process, press CTRL + C. All we need to do is run to compile our Sass code into CSS.

npm run compile-sass

Why not add a live reload to our project?

To do this run the following to install globally:

npm install live-server -g

Make sure you’re still in the sass project folder and run:

live-server

So you have a cool dev environment with your project running on HTTP locally. You must keep live servers and npm running compile sass in two separate terminal windows.

We've all set up our project environment now!

Sass Features

SASS effectively gives you a lot of the benefits of working with code but for stylesheets. Let's dive right in and take a look!

Variables

Variables are a way to reuse information throughout your style sheet. They enable us to store color values, fonts or any CSS value you want to reuse. We're using the $ symbol to make a variable. For example, we can define a color variable in our SCSS:

$my-color: #ffff00; //yellow
body {
  background-color: $my-color;

}

The alternative is finding and changing over each value individually...O_0

Nesting

If you look at the structure of an HTML file, you will notice that the hierarchy is very clear. On the other hand, the CSS does not have this visual structure. That's why it tends to get disorganized quite quickly. Enter the Sass nesting world! We can nest children in the parent selector by using nesting. This makes code much cleaner and less repeatable.

.navbar {
  background-color: blue;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}

Notice the indentation. You’ll see the ul and li selectors are nested inside the navbar selector.

Mixins

Mixins are another powerful feature of Sass. You can group multiple CSS declarations to be reused throughout your project by using mixins. Say we want to create a mixin that holds the transform property vendor prefixes. We would code it in Sass like this:

@mixin transform { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); }

To add the mixin into our code we then use the @include directive, for example:

.navbar {
  background-color: blue;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
    @include transform;
  }
}

All the code in the transform mixin will now be applied to the li element. You can also pass values into your mixins to make them even more flexible. Instead of adding a specified value, add a name to represent the value like so:

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

Now we can pass in whatever value we like whenever we call the mixin:

@include transform (rotate(20deg));

Functions

Much like JavaScript functions, Sass functions can receive arguments and return a value. For example:

@function divide($a, $b) {
  @return $a / $b;
}
div {
  padding: divide(80, 2) * 3px;
  height: 150px;
  width: 150px;
}

Partials & Import

Partials are a great way to modulate your CSS so that things can be maintained. Our sass is divided into separate files that represent different components. The name of a partial always begins with an underline. The partial is then imported using the @import directive.

We could make a part that only contains the code relevant to the header section, we would call it header.scss and move the corresponding code into the new file. Then we would import it back in main.css like this:

// in main.scss
@import 'header';

Inheritance / Extend

Another great feature of Sass is inheritance. We can extend CSS properties from one selector to another. For this, we use the @extend directive. See the following example:

.button {
  background-color: #0000FF;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 1.5rem;
}

This is pretty standard code for a CSS button. If say, throughout our document we have many different buttons, all of which are styled in a similar manner, we would have a good case for inheritance.

.button-secondary {
  @extend .button;
  background-color: #4CAF50; // Green
}  

‘&’ Operator

This ampersand & operator is frequently used for nesting and is a very useful feature.

.btn {
  display: inline-block;
  padding: 5px 8px;
  &--red {
    background-color: #ff0000; // Red
  }
  &:hover {
    background-color: #fff; // White
  }
}

How about Control Directives?

Sass uses control guidelines and expressions to include styles only under certain conditions. They are quite advanced and useful mainly in mixins. Common instructions are @if, @else, @for and @while.

@if and @else

The @if and @else directives are similar to if and else statements in JavaScript. @if takes an expression and executes the styles contained within its block — if the evaluation is not false (or null).

@for and @while

You can use the @for directive to execute a group of statements a specified number of times. It has two variations. The first uses the through keyword, it executes the statements from <start> to <end>.

 

So, you've learned what Sass is, how to install and run it on a local server, and we've looked at many of the features that make it a very useful addition to your front end capabilities. Using Sass, we write a lot of cleaner code, reuse code and reduce repetition, organize our projects more efficiently and even integrate logic into our stylesheets.

 We hope you found this article useful.

 

Business vector created by  freepik  - www.freepik.com

 
 

tags: Sass css Less guides


We use our own cookies and third-party cookies to improve our services, show products based on your preferences, analyse the browsing habits of our users, and enable interaction with social networks. Continuing to browse our sites implies full acceptance of their use. You can change your cookie setting or get more information here: Cookies policy .