CSS with superpowers? Working with Sass.

CSS with superpowers? Working with Sass.

Play this article

Intro

CSS is actually very fun and gives total control to the developer while developing websites but with time it become hard to maintain these stylesheets. This is where Sass can help.

One day when I was exploring a big project which uses Sass I noticed that the code was divided into different files such as _mixins.scss, _globals.scss, _variables.scss, and so on.

This was the time I realized that the code was very modular and maintainable which makes developer's as well as maintainer's life easy. Since each file had specific styles for specific purpose so it was easy to understand which file had which styles.

Today most companies use Tailwind, Bootstrap, MaterialUI, Sass, ShadCn UI, etc over plain CSS because maintaining that plain CSS can be a bit of a challenge.

Why Sass?

Sass (Syntactically awesome stylesheets) is a Preprocessor that is used with either .sass file extension or .scss extension.

Straight to the point -> Sass has features that don’t exist in CSS and it makes Sass very maintainable as well and less number of lines of code are need to be written to do the same thing in Sass.

Features like nesting, mixins, variables, partials, operators, functions, and more can help you write better code, maintainable code.

Also, the syntax of Sass is a superset of CSS, which means that any valid CSS code is also valid Sass code. This means you can take existing CSS code and incorporate it into a Sass file without any issues.

Features of sass

Variables

Variables in Sass are declared with a $ sign and also can be used with $ sign as well.

Here is a quick example:

:root {
  --primary-color: #007bff;
  --font-size: 16px;
  --secondary-color: #ffffff
}

body {
  background-color: var(--primary-color);
  font-size: var(--font-size);
}
$primary-color: #007bff;
$font-size: 16px;
$secondary-color: #ffffff

body {
  background-color: $primary-color;
  font-size: $font-size;
}

See the difference? The simplicity? That is literally what I call heaven. No more of these dashes -- and var again and again.

Nesting

Nesting in Sass helps a lot and it's literally my favorite feature of Sass.

For Example: Here we have targeted some classes and elements using simple CSS and then with Sass.

.container {
  background-color: #f0f0f0;
}

.container .header {
  font-size: 24px;
  color: #333;
}

.container .header a {
  text-decoration: none;
}

.container .content p {
  line-height: 1.5;
}

Instead, we can nest code inside the .container class like this 👇

.container {
    background-color: #f0f0f0;

    .header {
        font-size: 69px;
        color: #420;
    }

    .header a {
        text-decoration: none;
    }

    a {
      text-decoration: none;
    }

    .content p {
      line-height: 1.5;
    }
}

I know it might seem weird at first but once you start working and your CSS file becomes too big you will love Sass for this nesting feature.

Parent selector for block (&)

& in Sass is a special selector that refers to the parent selector of a declaration block.

It allows you to re-use the parent selector in more complex ways, such as adding pseudo-classes or combining it with other selectors.

For example:

.button {
  color: white;
  &:hover {
    background-color: black;
  }
}

/* Combine the parent selector with another selector */
.list-item {
  margin-bottom: 10px;

  & > .list-item-title {
    font-size: 20px;
  }
}

Here in the above snippet & is used to target the above parent which is button in this case so in the inside block &:hover means .button:hover because the parent of that block is button class and then with .list-item I used & > .list-item-title which means .list-item > .list-item-title (> means direct child).

Partials

Partials help in organizing our code into separate files which can be made with _filename.scss format. Partials are actually very helpful because in each partial file you can create styles for specific purpose and then import that file into the main sass file using the @import keyword.

Note: file should be saved with this format _filename.scss that is starting with a underscore and then with format and then this file can be imported in main sass file as "filename.scss" without underscore.

Some good examples of partial files that I prefer creating are:

  • _globals.scss

  • _variables.scss

  • _typography.scss

  • _buttons.scss

  • _reset.scss

  • and for each component you can do exactly this.

Mixins

Mixins are piece of code that is encapsulated and then can be reused whenever in the code with @include keyword. For example: you can write some code with @mixin and then reuse that piece of code again without writing it again and again.

Here is a quick example:

@mixin flex-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
}

.card {
  @include flex-container;
}

.aside {
  @include flex-container;
}

It works just like a utility class but this is included in the sass file instead of HTML so its more maintainable compared to utility classes.

Functions, Operators and other features

Functions are actually an overkill, me personally I don't prefer using functions in styles but here is a quick way how it can be done.

@function calculate-width($container-width, $columns) {
  @return $container-width / $columns;
}

.column {
  width: calculate-width(960px, 3);
}

Here in the above code snippet I declared a function using @function keyword which is calculator-width which accepts 2 parameters and returns the answer with @return keyword. Those who know a bit of programming concepts would definitely understand what this means here.

And then width is calculated and returned to the calculate-width function calling with 2 arguments 960px and 3.

You can use Operators as well. For example:

$base-font-size: 16px;

body {
  font-size: $base-font-size * 1.5;
}

Here you can see that the font-size is calculated and assigned to font-size property once its calculated. * here means multiplication as in any other programming language. Here $base-font-size which is 16px is multiplied by 1.5 to make 24px.

So the font-size becomes 24px and this is all done in a single line with that piece of code which calculated the size using asterisk operator *.

and..... You can even use if and else statements...

...

I know it became too much to handle right?? but its powerful right? yes it is.

Here is how decisions can be made using if-else statements in Sass.

$theme: light;

.button {
  @if $theme == light {
    background-color: white;
    color: black;
  } @else {
    background-color: black;
    color: white;
  }
}

Here in the above snippet I made a variable theme and assigned it light. Now we check and according to the theme we give the commands.

  • If (@if) theme is light make the background-color white and color of text black.

  • Otherwise (@else) make background-color black and color of text white since it will be either light theme or dark (in most of the cases).

Setting up live sass compiler in VS Code

Since the browser can't understand sass, so its needed to be compiled into CSS in order to work on browser.

There are many ways of doing this such as using tools like Gulp etc. however the way I prefer doing it is using Live sass compiler extension in VS Code. Once we done installing extension we will need to setup the path where sass is saved after compiling into CSS.

Steps to follow:

  • Install extension in VS Code called "live sass compiler"

  • Go to settings, and search for sass path

  • Now click on the edit in settings.json and you will see the following in .json file.

  • Edit the path according to your project need, it's the path where you want your compiled CSS to be saved. If you want your css into the styles folder then set the savePath to "/styles". Now save the path and restart the VS Code.

That's all you need to do, once this is done you will see a "watch sass" button at the bottom, when you want your sass to be compiled live, click on the watch sass button and it will compile the sass into css live while you work.

Note: You will see an extra file called ".map" file which is needed in order to compile that sass into the /styles folder so just ignore it.

Conclusion

If you found this article helpful, please consider sharing it. :)

Did you find this article valuable?

Support Shubh Sharma by becoming a sponsor. Any amount is appreciated!