The Journey of CSS and SASS Towards Serenity
Tags: webdev, css, sass, design
Published: 2024-02-19 15:23:34

In the ever-changing world of web design, CSS has undergone significant advancements, enabling designers and developers to craft visually captivating websites. The evolution of CSS has been remarkable, transitioning from a simple styling language to a powerful toolset for creating visually appealing websites. Yet, as web projects became more complex, developers faced challenges in managing styles effectively. 

There comes preprocessors like **SASS** (Syntactically Awesome Stylesheets) and its variant, **SCSS** (Sassy CSS), which revolutionized the way styles are written and maintained. Gone are the days of battling endless CSS declarations and specificity wars. SASS, a magical land where styles are organized, efficient, and simply delightful. With SASS, developers can take CSS to the next level, making styling tasks easier and more enjoyable. 

In this blog, we'll dive into the details of SASS, and see how it has revolutionized styling in modern web development.

> SASS is the most mature, stable, and powerful professional grade CSS extension language in the world (Extension of CSS3, To write Smarter and Dynamic CSS, To Write CSS like a programmer).

## SASS or SCSS? 🤔
SASS, born in 2006, to bring structure and superpowers to the CSS world. With SASS, developers were given two syntax options: `.sass ` and `.scss`. Though both offer similar functionality, they have some differences in usage.
- `.sass` opts for a more concise syntax, appealing to those who prefer a cleaner, indention-based structure (similar to what we see in Python).
- `.scss` adopts a syntax similar to CSS, making it more approachable for developers familiar with the CSS with curly braces and semicolons. It is newer and recommended.

![SASS Vs SCSS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5cucjkvsm1ccxybahc8.png)

Don't worry about the differences between the two flavors for now. Both achieve the same results, so choose whichever feels more comfortable to you! For this blog, we'll stick with the `.scss` syntax, which closely resembles normal CSS and is easier for beginners.

## Modern Browser Support 🌐
As web technologies evolve, browser support becomes pivotal for adopting new styling techniques. Luckily, modern browsers have warmly welcomed the features brought by SASS and SCSS, guaranteeing a smooth experience for developers. This broad support enables developers to fully utilize SASS's capabilities without concerns about compatibility.

## Let's dive deeper into the world of SASS! 👇
**CSS is typically more static**, although it does offer some native features like variables. Now, imagine SASS as a superhero for our CSS. It bestows upon us numerous superpowers, allowing us to transform our static CSS files into something dynamic, resembling a programming language. With SASS, we can incorporate concepts such as variables, functions, loops, and more, enhancing the dynamism and maintainability of our stylesheets.

> **NOTE**: SASS is a CSS preprocessor that allows us to write more powerful and maintainable CSS. However, browsers cannot directly read SASS files. We need to first convert them into normal CSS files that browsers can understand. While some modern browsers have built-in support for reading certain SASS features, it's still essential to learn them in order to use them effectively. 

If we use SASS with modern frameworks or libraries, they often handle the conversion process automatically. However, if we want to use SASS with our regular HTML files, we'll need to perform the conversion ourselves. In VSCode, there's a useful plugin called **live-sass-compiler** that can assist with this process. 

![Live Sass Compiler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/enctryf1r1qoat4xweex.png)https://marketplace.visualstudio.com/items?itemName=ritwickdey.live-sass

If we're working in a JavaScript application using Node.js, we can add SASS to our project using `npm` by running a command:
`npm install -g sass`

Let's explore the powers in detail! ✨

### 1) Variables 🔥
Imagine this: setting a color or font size once and being able to use it anywhere in our stylesheets. With variables, that's exactly what we can do! Say goodbye to the days of copying and pasting colors and fonts all over our CSS. By defining variables, prefixed with a `$` sign, we can set them once and reuse them throughout our stylesheets. This not only keeps our styles consistent but also makes them a breeze to update whenever needed, keeping our code organized and efficient.

```scss
//style.scss
$primary-color: #333;
$heading-font: 'Roboto', sans-serif;

body {
  color: $primary-color;
  font-family: $heading-font;
}
```
See how we define variables for color and font, and then use them throughout! Change the variables, and our entire site updates like magic!

> **NOTE**: In plain CSS, we can define variables using the traditional `var` method, but many developers are not familiar with this approach or haven't used it in their projects. However, it's essential to be aware of native elements like this. 
More information on: https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties.

### 2. Nesting 🔥
Tired of writing long chains of selectors? Nesting lets us indent our styles to mirror our HTML structure, making our code more readable and intuitive.

```scss
//style.scss
nav {
  background-color: #f2f2f2;
  padding: 10px;
  ul {
    list-style: none;
    li {
      display: inline-block;
      margin: 5px;
      &:hover {
        color: #fff;
      }
      &::after {
        content: "Test";
      }
    }
  }
}
```
Notice how the styles for the `nav` and its nested elements closely mirror the HTML structure, making our code incredibly readable! (It's worth mentioning that modern browsers now have native support for reading style nesting).

Also, note the usage of pseudo-selectors like `:hover` and `::after` with the `&` symbol. The `&` symbol is a special feature in SASS known as the parent selector reference. It is used to concatenate the parent selector with the nested selector.

### 3. Mixins 🔥
Are you tired of repeating the same styles over and over again? With mixins, we can create reusable code snippets for common styles, just like functions. They're our secret weapon for **DRY** (Don't Repeat Yourself) coding, helping us save time and effort.

```scss
//style.scss
@mixin button-style {
  padding: 5px;
  border: 1px solid #ddd;
  font-size: 12px;
  cursor: pointer;
}

.btn {
  @include button-style;
  background-color: #4CAF50;
  color: #fff;
}

.red-btn {
  @include button-style;
  background-color: #f44336;
}
```
The `button-style` mixin defines common styles for buttons, then we use it in `.btn` and `.red-btn` with specific colors. DRY power!
Take note of the usage of the `@mixin` and `@include` keywords. `@mixin` keyword is used to define a mixin, and `@include` keyword is used to include a mixin within a selector.

As mentioned earlier, mixins in SASS are similar to functions and can accept parameters. Let's explore another example:

```scss
//style.scss
@mixin flexclasses($direction, $bgcolor) {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: $direction;
    background-color: $bgcolor;
}

.section1{
    @include flexclasses(column, rgb(207, 49, 49));
    margin: 20px 0;
}

.section2{
    @include flexclasses(row, rgb(52, 52, 219));
    margin: 40px 0;
}
```
In this example, the `flexclasses` mixin accepts two parameters: `$direction` and `$bgcolor`. When we `@include` the mixin in the `.section1` and `.section2` selectors, we provide specific values for these parameters. This allows us to customize the behavior of the mixin based on the needs of each selector.

> **NOTE**: In SASS, all keywords, such as `@mixin`, `@include`, and so on, begin with the `@` symbol. This symbol distinguishes them from regular CSS syntax and identifies them as SASS-specific directives or features.

### 4) Partials/Modules 🔥
Partials in SASS ensure modularity by breaking down a large file into smaller, more manageable files. For example, we can create partial files like `_variables.scss` and `_mixins.scss` to modularize our codebase and handle complex styles more effectively. This approach promotes code reusability and maintainability.

In the examples provided, our variables and mixins are currently placed in the same `style.scss` file. To enhance modularity, we can separate them into different partials. Here are the partials we can create:

```scss
//_variables.scss
$primary-color: #333;
$heading-font: 'Roboto', sans-serif;
```
```scss
//_mixins.scss
@mixin button-style {
  padding: 5px;
  border: 1px solid #ddd;
  cursor: pointer;
}
@mixin flexclasses($direction, $bgcolor) {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: $direction;
    background-color: $bgcolor;
}
```
These partial files can then be included in the `style.scss` file using the `@import` directive, allowing us to organize our codebase more efficiently and improve overall maintainability.

```scss
//style.scss
@import './variables';
@import './mixins';

// Rest of the styles...
```
When creating partials in SASS, it's a convention to prefix the file names with an underscore (_). For example, `_variables.scss` and `_mixins.scss`. This helps distinguish partial files from regular SCSS files and indicates to other developers that these files are meant to be imported into other SCSS files rather than compiled separately.

### 5) Inheritance 🔥
Think of styles as building blocks that we can build upon. With inheritance in SASS, we can define base styles and then extend them with specific modifications. This keeps our code DRY (Don't Repeat Yourself) and makes it easier to maintain and update in the long run.

```scss
// style.scss
.big-btn {
  @extend .btn;
  font-size: 24px;
}
```
We defined a `.btn` class earlier, the `.big-btn` inherits all styles from `.btn` using `@extend`, then just adds a bigger font size. No code duplication!

### 6) Looping 🔥
Need to style a bunch of elements the same way? Loops let us generate repetitive styles in a flash. They automate repetitive styles, saving us time and ensuring consistency.

```scss
// style.scss
@for $i from 1 to 6 {
  h#{$i} {
    color: blue;
  }
}
```
In the provided code snippet, we use a normal `for` loop with SASS syntax to style all headings from `h1` to `h6` with the color blue in just one line!

The dynamic usage of the current variable inside the loop is achieved using `#{$i}`. This **interpolation** syntax(with `#`) allows us to insert the current value of the variable `i` directly into the selector, generating styles for each heading dynamically.
This demonstrates the power and flexibility of SASS loops in automating repetitive styling tasks with ease.

See another example:

```scss
// style.scss
@for $i from 1 through 10 {
  .m#{$i} {
    margin: #{$i}px;
  }
  .mt-#{$i} {
    margin-top: #{$i}px;
  }
}
```
Another example of a concise SASS loop. Can you guess what the compiled output will be?

Indeed, it will generate margin classes from `.m1` to `.m10` and corresponding margin-top classes from `.mt-1` to `.mt-10`, with pixel values ranging from `1px` to `10px` assigned as their values. And if we need classes up to `.m100`, there's no need to worry. We can easily achieve that by adjusting the loop parameter from 10 to 100.

This illustrates the efficiency of using loops to generate such classes. Do you see the power and flexibility they provide?

Let's explore another example with a different type of loop:

```scss
// style.scss
$menu-items : home about services contact newitem;
@each $item in $menu-items {
    .#{$item}{
        color:hotpink;
    }
}
```
In this example, we use the `@each` directive to iterate over each item in the `$menu-items` list. For each item, we dynamically generate a CSS class with the item's name as its selector and apply a common style of `color: hotpink`. This approach allows us to efficiently apply styles to multiple elements based on a predefined list.

Feel free to explore other SASS loops and their usage if you're more curious about their capabilities!

## Conclusion 🤔🙌
In simple terms, SCSS(or SASS) is like a supercharged version of CSS that makes styling websites easier and more efficient. With SCSS, developers can use handy features like variables, nesting, and mixins to write cleaner and more organized code. Whether you're new to web development or a seasoned pro, learning SCSS is essential for keeping up with the latest trends and making our projects shine. And the best part? It's not too complicated to pick up and start using right away!

This blog offered just a glimpse of SASS's potential, based on my learnings. I understand it's not a new subject; SASS has been around for a while. The recent motivation to revisit and write this blog came from a colleague who asked me about SASS.😊

Are you interested in further exploration? If so, here are some additional resources to consider:
_SASS Documentation:_
https://sass-lang.com/documentation/
_Interactive SASS Playground:_
https://sass-lang.com/playground
https://www.sassmeister.com/

So, say goodbye to CSS chaos and welcome the serenity of SASS! Our stylesheets will appreciate the switch.😉🔥


Thanks for reading. 🙌
Happy Coding! 🚀👨‍💻✨