The Main Features of SASS
Tags: sass, codenewbie, webdev, beginners
Published: 2020-10-22 01:05:38

SASS effectively gives us a lot of the programmatic benefits of working with code, only now with the ability to apply it to stylesheets. 

In this post, we'll be diving right into the features of SASS, including:

- Variables 
- Nesting
- Mixins
- Functions
- Partials & Importing
- Inheritance
- The '&' Operator
- Control Directives
- Interpolation
- Placeholders

Let's get started!

## SASS Variables

**Variables** are a way to store information that you want to reuse throughout your stylesheet. 

They allow us to store values for colors, fonts or really any CSS value that you want to reuse!

We use the `$` symbol when we wish to make something a variable. 

Let's see an example!

In our SCSS, define a color variable like so:

```SASS
$color-primary: #ffff00; // Yellow

body {
  background-color: $color-primary;
}
```

This will of course, set our `background-color` to yellow. It's that simple! 

*Note:* You can use single line comments in Sass with `//`. 

When we then run our compile, it’ll output the following CSS:

```SASS
body {
  color: #ffff00;
}
```

This becomes extremely powerful when working on large projects! 

If you wish to make a change to a colour used throughout your stylesheets, it’s much simpler to alter if the color is defined in one location, as a single variable.

The alternative to changing the value of one variable defined at one location, is finding and replacing every reference to the value you want to change. This is a much more tedious task, especially if you want to implement a quick change, to test out a different color or font.

## Nesting

When you observe the structure of an HTML file, you’ll notice it has a very clear hierarchy:

```HTML
<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
<body>
 
<h1>My First Heading</h1>
<p>My first paragraph.</p>
 
</body>
</html>
```

As you can see, HTML has a structure that makes it quite easy to read.

CSS on the other hand, lacks this visual structure. Which is why it has a tendency to become disorganized quite quickly. 

Enter Sass nesting!

### Definition

Using nesting, we can nest child selectors inside of the parent selector.

This results in much cleaner and less repetitive code.

### Example

Take the following HTML:

```HTML
<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Store</li>
    <li>Contact Us</li>
  </ul>
</nav>
```

Using regular CSS, we would write this like so:

```css
.navbar {
  background-color: orangered;
  padding: 1rem;
}
.navbar ul {
  list-style: none;
}
.navbar li {
  text-align: center;
  margin: 1rem;
}
```

There’s a lot of repetition here. Each time we want to style a child of `navbar`, we have to repeat the class name.

With Sass nesting, we can write much cleaner code.

Like so:

```sass
.navbar {
  background-color: orangered;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}
```

Using indentation, you can now see the `ul` and `li` selectors are neatly nested inside the `navbar` selector.

We have a much less repetitive syntax, which is far easier to read! 


## SASS Mixins

Mixins are an extremely powerful feature of Sass. We use them to group together multiple CSS declarations for reuse throughout our projects.

Say we want to create a mixin to hold the vendor prefixes for a transform property.

In SASS, we’d code it like so:

```SASS
@mixin transform {
  -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  transform: rotate(180deg);
}
```

To add the mixin into our code, we then use the `@include` directive, like so:

```SASS
.navbar {
  background-color: orangered;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
    @include transform;
  }
}
```

All the code in the transform mixin will now be applied to the `li` element. You can also pass values into your mixins to make them even more flexible.

Instead of adding a specified value, add a name (using a variable, like `property`) to represent the value like so:

```SASS
@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}
```

Now we can pass in whatever value we like, whenever we call the mixin:

```SASS
@include transform (rotate(20deg));
```

## SASS Functions

Sass **functions** can receive arguments and return a single value.

They add an element of programming to writing CSS code, and we can now do math!

The standard math operators `+`, `-`, `*`, `/`, and `%` can all be utilized.

### An example function

The following function can accept two arguments, `$first-number` and `$second-number`. The value that is returned by the function is the sum of the two variables:

```SASS
@function add-numbers($first-number, $second-number) {
  @return $first-number + $second-number
}
```

Say we want to replace the value of a `padding` property with the sum of two separate values.

We would call our function and pass in the arguments like so:

```SASS
.box1 {
  padding: add-numbers(5px, 10px);
}
```

The resulting CSS output would be:

```CSS
.box1 {
  padding: 15px;
}
```

Lets see the full code:

```html
<html>
  <head>
    <title>Page Title</title>
  </head>
<body>
<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Store</li>
    <li>Contact Us</li>
  </ul>
</nav> 
</body>
</html>
```

And our SASS:

```sass
@function add-numbers($first-number, $second-number) {
  @return $first-number + $second-number
}

.navbar {
  background-color: orangered;
  padding: add-numbers(5px, 100px);
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}
```

As you can see, functions help you write more readable and DRY Sass, as you can utilize reusable logic in a very efficient manner. This can make a huge difference when you start working on larger and more complex projects!

## SASS Partials & Importing

Partials in SASS help us to break up our files into smaller files without affecting performance.

The use of partials allows us to modularize our CSS, to help keep things maintainable.

We divide up our Sass into separate files representing different components. A partials’ name will always start with an underscore `_`. We then import the partial using an `@import` directive.

### Using Partials

Let’s say our Sass file is getting rather large. We might choose to make a partial file that contains just the code that’s relevant to the header section; we’d call it `_header.scss` and move the appropriate code into that new file.

We would then import it back into `main.css`, like so:

```SASS
// In main.scss
@import 'header';
```

*Note:* When you import a file, there’s no need to include the `_` or `.scss` file extension.

### @import in CSS vs SASS

The `@import` directive is of course, also available in CSS. However, there is an important difference. Whenever an import statement is used in CSS, an HTTP request is made to the server. This increases the amount of resource requests and negatively affects the performance of a web page. SASS does not do that. SASS takes the file that you want to import from and combines it with the file you’re importing. So you can serve a single CSS file to the web browser, which does not affect the performance.

## SASS Inheritance

Another great feature of Sass is **inheritance**. We implement this using the `@extend` directive.

Inheritance is a feature of SASS that allows multiple classes to share a common set of properties with one another.

### An Example

Some typical CSS code for styling a button:

```CSS
.button {
  background-color: #0000FF; // Blue
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 1.5rem;
}
```

If we happen to have a number of buttons on our website, all of which are styled in a similar manner, we would have a good case for inheritance!

We would implement a secondary button via inheritance like so:

```SASS
.button-secondary {
  @extend .button;
  background-color: #4CAF50; // Green
}  
```

Our `.button-secondary` class will take on all of the properties and values set the `.button class`, with the exception of `background-color` which we’ve decided to set to green.

The use of inheritance helps us to keep our code neat, clean and focused on constructing reusable components.

## The '&' Operator in SASS

The ampersand `&` operator is often used when [nesting](https://www.easeout.co/blog/2020-07-16-nesting-in-sass) in SASS and is an extremely useful feature.

It can be a great time-saver, especially if you happen to be coding your stylesheets with the [BEM methodology](http://getbem.com/introduction/), or using any systematic naming convention for your class names.

See the following HTML:

```HTML
<button class = "btn btn--red"> Click me! </button>
```

Typical styling would be something like this:

```CSS
.btn {
  display: inline-block;
  padding: 15px 32px;
}
.btn--red {
  background-color: #ff0000; // Red
}
.btn:hover {
  background-color: #fff; // White
}
```

With the `&` operator we can be much more efficient:

```SASS
.btn {
  display: inline-block;
  padding: 15px 32px;
  &--red {
    background-color: #ff0000; // Red
  }
  &:hover {
    background-color: #fff; // White
  }
}
```
Notice that we’ve now nested the child selectors that use the same `.btn` name, represented by the `&` operator. name.

When compiled the `&` operator will be replaced by its enclosing selector name!

## Understanding SASS Control Directives

Control directives and expressions are used in SASS to include styles only under certain defined conditions.

As a feature, they’re quite advanced and are mainly useful in mixins. Common directives include `@if`, `@else`, `@for` and `@while`.

### @if and @else

The `@if` and `@else` directives are similar to `if` and `else` statements in JavaScript.

`@if` takes an expression and executes the styles contained within its block — if the evaluation **is not false** (or null).

`@else` will then be checked, if the previous `@if` evaluated to false.

For example:

```sass
@mixin heading($size) {
  @if $size == large {
    font-size: 4rem;
  }
  @else if $size == medium{
    font-size: 3rem;
  }
  @else if $size == small {
    font-size: 2rem;
  }
  @else {
    font-size: 1rem;
  }
}
 
.h1 {
  @include heading(large);
}
 
.h6 {
  @include heading(small);
}
```
Here, we are using a *heading* mixin which accepts `$size` as an argument. We can have a different size for each of our headings depending on which value we pass to the mixin.

### @for

You can use the `@for` directive to execute a group of statements a specified number of times. Effectively this is a loop.

It has two variations. The first uses the `through` keyword, it’ll execute the statements from start to end, inclusive.

An example using through:

```sass
@for $i from 1 through 5 {
   .list-#{$i} {
      width: 2px * $i;
   }
}
```

This will produce the following CSS output:

```css
.list-1 {
  width: 2px; 
}
 
.list-2 {
  width: 4px; 
}
 
.list-3 {
  width: 6px; 
}
 
.list-4 {
  width: 8px; 
}
 
.list-5 {
  width: 10px; 
}
```

If we replace the `through` keyword with `to`, it makes the loop exclusive. The difference being that it won’t execute when the variable is equal to **end**.

An example using `to`:

```sass
@for $i from 1 to 5 {
   .list-#{$i} {
      width: 2px * $i;
   }
}
```

This produces the following CSS:

```css
.list-1 {
  width: 2px; 
}
 
.list-2 {
  width: 4px; 
}
 
.list-3 {
  width: 6px; 
}
 
.list-4 {
  width: 8px; 
}
```

### @while

We could instead implement the above code using the `@while` directive. As its name implies, it will continue to output CSS produced by the statements while the condition returns true.

The syntax is as follows:

```sass
$i: 1;
@while $i < 6 {
  .list-#{$i} {       
     width: 2px * $i;   
  }
  $i: $i + 1;
}
```

The output is identical, so you could opt for your personal preference based on the syntax.

## SASS Interpolation

Interpolation is essentially a code insertion. It allows us to interpolate SASS expressions into our code. We can use it to use a selector or property name, quoted or unquoted strings etc, as variables.

### The syntax

To interpolate an expression we need to wrap the expression using `#{ }`.

```SASS
#{$variable_name}
```

Let’s see an example that shows how we could use interpolation with a mixin:

```SASS
@mixin interpolation($editable, $val, $val2, $prop1, $prop2)
{
    background-#{$editable}: $val;
    position: $val2;
    #{$prop1}: 0px; 
    #{$prop2}: 0px;
}
 
 
.block1{
    @include interpolation("image", url("img.png"), absolute, top, right);
}
 
.block2{
    @include interpolation("color", lightgray, absolute, top, left);
}
```

This will compile in CSS as follows:

```CSS
.block1 {
    background-image: url("img.png");
    position: absolute;
    top: 0px;
    right: 0px;
}
  
.block2 {
   background-color: lightgray;
   position: absolute;
   top: 0px;
   left: 0px;
}
```

As you can see, it’s quite easy to use this to create dynamically reusable code!

### Main reasons to use Interpolation

* We can use dynamically created names as a property name, a variable name or for other similar purposes.
* We can create highly reusable code!

## SASS Placeholders

In SASS a **placeholder** looks and acts a lot like a class selector, only it starts with a `%` and it is not included in the CSS output.

Our `%placeholder` selector contains some width and height declarations:

```SASS
%placeholder {
    width: 100%;
    height: 100%;
}
body {
    @extend %placeholder;
}
p {
    @extend %placeholder;
}
```

Note that we’ve used the `@extend` directive, which allows one selector to inherit styles of another selector.

This outputs to CSS as follows:

```CSS
body, p {
    width: 100%;
    height: 100%;
}
```

Simple and as expected!

However, the preprocessor will skip `%placeholder` and it won’t be included in the final CSS file.

### Why use Placeholders? 

Placeholder selectors are mainly useful when writing a SASS library where each style rule is optional.

Typically, when working on your own project, it’s often better to just extend a class selector instead. But it’s good to know, as it could come in quite handy if you start working on larger-scale projects.

## Wrapping up

And thats it! Congratulations for making it this far 😅, this ended up being quite a lengthy article! I hope you now have more of an understanding about what you can do with SASS.

In my next article, we’ll learn how to structure our SASS projects! 

---
_**Are you ready to turn your dev skills into a freelance business?** Whether you're completely new to freelancing or are looking to level up your existing skills. I'll teach you everything you need to know to become a successful freelancer!_

Get started today with my [Complete Guide to Freelancing](https://easeout.gumroad.com/l/freelance).


![Complete Guide to Freelancing package](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8jx3gvzvjazn8z1mbjm.png)

> Available now at 👉 [https://easeout.gumroad.com/l/freelance](https://easeout.gumroad.com/l/freelance)

## A little about me..

Hey, I'm Tim! 👋 I'm a freelance business owner, web developer & author. 

I teach both new and experienced freelancers how to [build a sustainable and successful freelancing business](https://easeout.gumroad.com/l/freelance). If you'd like to read more of my articles, check them out on [my blog](www.easeout.co).

Thanks for reading 🎉