Getting started with SCSS - The CSS Preprocessor with Superpowers
Tags: webdev, css
Published: 2023-08-19 14:46:11

Have you ever written lines of CSS code, and felt there should be a way to make writing CSS easier and faster? This is where SCSS (Sassy CSS) comes in. Have you thought of nesting HTML elements inside their specific parent element? Well, SCSS was made for this feature. You got to admit it is a very good feature that makes writing CSS easier for web developers.  In this article, we will discuss a lot of features SCSS offer and much more.

## Prerequisites

- A basic knowledge of HTML and CSS (you've built at least one basic webpage with them).

- A code editor (VS Code recommended).

- And a browser (Chrome or Firefox recommended).

## Why SCSS?
SCSS (Sassy CSS) is a preprocessor scripting language that is compiled into regular CSS. It extends the capabilities of CSS by adding features like variables, nesting, mixins, and more. Below are some reasons why you might consider using SCSS over plain CSS for styling both static and dynamic web pages.

1. **Variables:** SCSS allows you to define variables, which can be very useful for storing reusable values such as colors, font sizes, and spacing. This makes it easier to maintain consistency across your styles and change values in a single place.

2. **Nesting:** SCSS allows you to nest your CSS rules within parent selectors. This can help improve the readability of your styles and make them more organized, especially for complex structures.

3. **Mixins:** Mixins allow you to define reusable blocks of styles that can be included in multiple places. This can help reduce duplication of code and make your styles more maintainable.

4. **Partials and Imports:** SCSS supports breaking your styles into smaller, modular files called partials. You can then use the `@import` directive to combine these partials into a single CSS file. This can make your codebase more organized and manageable.

5. **Mathematical Operations:** SCSS allows you to perform arithmetic operations on values, which can be useful for calculations such as responsive layouts, spacing adjustments, and more.

6. **Functions:** SCSS provides a set of built-in functions that allow you to manipulate values, perform color calculations, and more.

7. **Conditional Statements:** SCSS supports if/else statements and loops, which can be useful for creating dynamic styles based on certain conditions.

8. **Readable Syntax:** Most developers find SCSS's syntax more readable and intuitive than regular CSS. The nesting and structure can make your code easier to understand, especially for complex styling scenarios.


However, it's important to note that the decision to use SCSS over plain CSS depends on the needs and nature of your project and your personal preferences. If you're working on a small project with minimal styling requirements, plain CSS might be sufficient. On the other hand, for larger and more complex projects, SCSS can offer many advantages that contribute to a more efficient and maintainable styling workflow.

## What is SCSS?
SCSS, which stands for "Sassy CSS," is a CSS preprocessor scripting language that adds extra features and capabilities to standard CSS. It was developed to make writing and managing stylesheets more efficient and powerful. SCSS is a superset of CSS, meaning that any valid CSS is also valid SCSS, but SCSS extends CSS with additional features.

SCSS was first developed by **Hampton Catlin in 2006** and later maintained by **Natalie Weizenbaum in 2009**. The language was designed to address some of the limitations and challenges of writing complex and maintainable CSS. SCSS is also known as **"SASS"** which stands for **Syntactically Awesome Stylesheets**

## How to install SCSS
SCSS can be installed by downloading the [Live Sass Compiler](https://marketplace.visualstudio.com/items?itemName=ritwickdey.live-sass) extension in VS Code Editor.
The Extension can also be installed by following the following steps:

- Open VS Code Editor
- Press Ctrl + P on your keyboard
- type in `exe install glenn2223.live-sass`

![A screenshot of the live sass compiler marketplace](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzje8snbtdw46m2vwc0y.png)

## How SCSS is compiled
Looking at the image below, SCSS is compiled by clicking on `Watch Sass` from the Statusbar. This activates live compilation of SCSS and then you can click `Stop Watching Sass` from Statusbar to turn off live compilation.

All the SCSS code written in the main.scss file will be compiled in the `main.css` file in the `/dist/css` folder

![A screenshot of a project which SCSS was used](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/half95l0ucrq27o3qcmv.png)

**Note:** SCSS files are saved with the extension .scss for example (style.scss). Also, the file reuired for linking with the HTML is the `main.css` file with the directory `./dist/css/main.css` file, and note that the `main.scss` file which is being compiled. Also, the `main.scss` file needs to be created first before writing any SCSS code at all.

## Nesting in SCSS
One of the reasons why most web developers make use of SCSS is because of its Nesting feature. SCSS allows you to nest your CSS rules within parent selectors. This can help improve the readability of your styles and make them more organized, especially for complex structures.
For example, let's create a simple HTML page with two elements; a parent element and a child element

```
<body>
    <div class="parent">
        <div class="child"></div>
    </div>
</body>
```
Let's add some styles and nest the two elements together

```
.parent {
    padding: 2rem;
    background-color: red;

    .child {
        background-color: blue;
        padding: 1rem;
    }
}
```
The result of the above code is shown below

![The result of the above code shown on a chrome browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5qqawv75iaxtihvusik.png)

Let's add a hover state to the parent element

```
.parent {
    padding: 2rem;
    background-color: red;

    .child {
        background-color: blue;
        padding: 1rem;
    }

    &:hover {
        background-color: yellow;
    }
}
```
The ampersand symbol (`&`) is used as a placeholder to select the current or parent selector in nested rules.

## Declaring Variables in SCSS
Variables are declared in SCSS using the `$` symbol. Referring to the HTML page above, below is a simple way of using variables in SCSS.

```
$color-primary: red;
$color-secondary: blue;
$padding-large: 2rem;
$padding-small: 1rem;

.parent {
    padding: $padding-large;
    background-color: $color-primary;

    .child {
        background-color: $color-secondary;
        padding: $padding-small;
    }
}
```
Unlike CSS, declaring variables in SCSS is very easy and these variables can be saved as partials which can be used anywhere. We'll dive more into partials later in the article.

## Using Mixins in SCSS
Mixins are a powerful feature of SCSS that allows you to define reusable blocks of CSS properties and rules. These blocks can then be included in different parts of your stylesheets. Mixins are particularly useful for reducing code duplication, promoting modular design, and making your stylesheets more maintainable.

Below is how mixins work in SCSS:

**Defining a Mixin:** Mixins can be defined using the `@mixin` directive followed by a name and a set of CSS properties and rules. Here's an example of a simple mixin:

```
@mixin box-shadow($x, $y, $blur, $color) {
  box-shadow: $x $y $blur $color;
}

```
**Using a Mixin:** The above mixin can be used in a stylesheet by using the `@include` directive, followed by the name of the mixin and any arguments it requires. Here's an example:

```
.parent {
  @include box-shadow(2px, 2px, 5px, rgba(0, 0, 0, 0.2));
}
```
In the above example, the `box-shadow` mixin is included in the `.parent` class, applying the specified box-shadow properties.

## Functions in SCSS
SCSS functions are another powerful feature that enables you to perform calculations, manipulate values, and create dynamic styles. SCSS provides built-in functions as well as the ability to create custom functions. Functions in SCSS work similarly to functions in programming languages, accepting inputs (arguments) and returning values.

Below is an example of how functions work in SCSS;
**Built-In Functions**: SCSS comes with a variety of built-in functions that you can use to manipulate values, perform calculations, and modify styles. Some examples of built-in functions include `lighten()`, `darken()`, `rgba()`, `round()`, `percentage()`, `mix()`, and many more.

```
$color: #3498db;

.lighter-color {
  background-color: lighten($color, 20%);
}

```
**Custom Functions:** SCSS also enables you to create custom functions using the `@function` directive. Custom functions can accept arguments, perform calculations or logic, and return values. Here's an example of a custom function that converts pixel values to rems:

```
@function px-to-rem($pxValue, $baseFontSize: 16px) {
  @return ($pxValue / $baseFontSize) * 1rem;
}

.text {
  font-size: px-to-rem(18px);
}

```

## How partials work in SCSS
In SCSS, partials are a way to break your stylesheets into smaller, modular files for better organization and maintainability. Partial files in SCSS are typically prefixed with an underscore (_) and have a .scss extension. They contain segments of CSS code that can be included and combined into a main SCSS file using the `@import` directive.

Below is how partials work in SCSS

1. 
**Creating Partial Files:** Partial files are meant to hold specific sections of your styles, such as typography, colors, layout, etc. To create a partial file, you give it a name that starts with an underscore and ends with `.scss`. For example, `_variable.scss`.

2.
**Defining Styles in Partials:**
In the partial file, you can define your styles just like you would in a regular SCSS file. For example, _variables.scss might contain color and font-related styles:

```
// _variables.scss

$base-font-size: 16px;
$color-primary: red;
$color-secondary: blue;
$padding-large: 2rem;
$padding-small: 1rem;

body {
  font-family: Arial, sans-serif;
  font-size: $base-font-size;
}

```
3.
**Importing Partials:** To include the styles from a partial file into your main SCSS file, you use the `@import` directive without the underscore and extension. When you import a partial, you don't need to include the _ or .scss in the import statement.
// main.scss

```
@import 'variables';

.parent {
    padding: $padding-large;
    background-color: $color-primary;

    .child {
        background-color: $color-secondary;
        padding: $padding-small;
    }
}
```

## Inheritance in SCSS
SCSS also makes it possible for properties to be inherited from the parent element to the child element using the `@extend` directive followed by the element selector
Here's how Inheritance works in SCSS

```
.parent {
    display: flex;
    justify-content: center;
    align-items: center;

     .child {
        @extend .parent;
        flex-wrap: wrap;
     }
}
```
In the above code, all properties of the `.parent` element will be inherited by the `.child` element, this is similar to mixins but there's a slight difference because mixins are more flexible.

Want to know more about SCSS?, click on the link below and follow the SCSS course by @codestackr    -   [Link](https://youtu.be/_a5j7KoflTs)