SCSS Guide for a beginner (Part 1).

What is SCSS

SCSS/SASS is a preprocessor for CSS which gives wings to CSS, It transpiles SCSS code to CSS. Writing CSS for multipage website leads to larger stylesheets, which gets hard to maintain. So we can make use of SCSS features such as mixins, partials, inheritance and lot more to avoid writing the same CSS code every time. It helps us to use complex logical syntax like – variables, functions, mixins, code nesting, and inheritance to name a few, supercharging your vanilla CSS.

Installation

image.png

Or

  • install it globally with this command npm i -g sass after installation, you have to run sass --watch input.scss output.css command to compile/transpile the SCSS to CSS.

Features

  • SCSS Variables

Use $ to create variables and use them in stylesheets.

$font-color: #fff; $bg-color: #00f; .box{ color: $font-color; background: $bg-color; }

  • module system

With help of SCSS modules, we can break the CSS code into multiple modules to maintain them and again import them into one file to ship them to the user. For ex.,

_colors.scss → to store color custom props, _component.scss → to store styles related to components, _utils.scss → to store utility classes

We put _ (underscore) before a file name as a partial, which tells the compiler not to compile them. To use the files in other files, we make use of @use. Syntax: @use 'filename.scss' as name_space name space could be any alphabet or word, to use the styles we have to refer the namespace before style. ` // src/_corners.scss $radius: 3px;

@mixin rounded { border-radius: $radius; } // style.scss @use "src/corners" as c;

.button { @include c.rounded; padding: 5px + c.$radius; } `

We can also make use of @use as * in this case we don't have to write any namespace before using it, but it is recommended to use as a individual or if you have team members working on same project then it would cause name conflicts.

`// src/_corners.scss $radius: 3px;

@mixin rounded { border-radius: $radius; }

// style.scss @use "src/corners" as *;

.button { @include rounded; padding: 5px + $radius; } `

  • Nesting :

Nesting is one of the feature that everyone is in love with, take a look at below code snippet, .post{ border:1px solid red; &-header{ color:red; } &-body{ background:#ccc; } }

This will create three classes .post, .post-header & .post-body, the & symbol gets replaced with the parent component class name, we can nest the classes into as much deep as we want, but it is advisable to nest the classes at three level only.

You can read about other Features of SCSS such as mixins, partials and inheritance here

Thank You.