Css has a very powerful syntax but can sometimes become an outright mess on more complex websites. CSS preprocessors like Sass has syntax that helps developers to write cleaner and more readable code in CSS.
Sass (Syntactically awesome style sheets) is a CSS preprocessor that lets you use mathematical operations, variables, functions, loops, imports and other useful functionalities.
We will talk about Scss (Sassy CSS) which is one of two syntaxes available in Sass. Let me elaborate further:
Standard CSS doesn’t support nesting. It’s not possible to write a class inside of another class. As projects get larger, readability and structure become an issue.
Nesting allows for a cleaner method of targeting DOM elements. It also reduces the time to write your styles because you don’t have to rewrite selectors multiple times.
Nested styles look something like this:
Scss also gives you the ability to use variables to store a value or a set of values and to reuse these variables throughout your Scss files. It’s a very powerful and useful tool.
For example, let’s say you are building a website and want to use #66CCCC as a color and Helvetica as a font on your buttons and h1s. You can do something like this:
Mixins are Scss functions that allow you to store multiple CSS declarations which we can use like variables.
For example, we can group a font selection like following:
We can even create a mixin and add parameters:
After creating the mixin, we can use it in any class with @include command. That would look something like this:
In larger projects, it’s important to keep our code in more defined sections. With Scss, you can split your code into multiple Scss files and include them in your main Scss file using the @import command.
The main Scss file that you will create should be included in the webpage and from this file, other style modules can be imported like so:
These are just some of the important features of Scss which will help us write cleaner and more efficient code. After I started using Scss, it changed my whole approach on how I write CSS but in a great way. I highly recommend to get your hands dirty with Scss and explore the possibilities. It’s easy to pick up and a great tool to have in your frontend arsenal.
If you want to get started, you can directly start coding on codepen.io. I hope you found this article helpful.