DEV Community

Cover image for The Main Features of SASS
Timothy Robards
Timothy Robards

Posted on • Updated on • Originally published at easeout.co

The Main Features of SASS

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:

$color-primary: #ffff00; // Yellow

body {
  background-color: $color-primary;
}
Enter fullscreen mode Exit fullscreen mode

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:

body {
  color: #ffff00;
}
Enter fullscreen mode Exit fullscreen mode

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:

<!DOCTYPE html>
<html>
  <head>
    <title>Page Title</title>
  </head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

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:

<nav class="navbar">
  <ul>
    <li>Home</li>
    <li>Store</li>
    <li>Contact Us</li>
  </ul>
</nav>
Enter fullscreen mode Exit fullscreen mode

Using regular CSS, we would write this like so:

.navbar {
  background-color: orangered;
  padding: 1rem;
}
.navbar ul {
  list-style: none;
}
.navbar li {
  text-align: center;
  margin: 1rem;
}
Enter fullscreen mode Exit fullscreen mode

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:

.navbar {
  background-color: orangered;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

@mixin transform {
  -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  transform: rotate(180deg);
}
Enter fullscreen mode Exit fullscreen mode

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

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

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:

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}
Enter fullscreen mode Exit fullscreen mode

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

@include transform (rotate(20deg));
Enter fullscreen mode Exit fullscreen mode

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:

@function add-numbers($first-number, $second-number) {
  @return $first-number + $second-number
}
Enter fullscreen mode Exit fullscreen mode

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:

.box1 {
  padding: add-numbers(5px, 10px);
}
Enter fullscreen mode Exit fullscreen mode

The resulting CSS output would be:

.box1 {
  padding: 15px;
}
Enter fullscreen mode Exit fullscreen mode

Lets see the full code:

<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>
Enter fullscreen mode Exit fullscreen mode

And our 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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

// In main.scss
@import 'header';
Enter fullscreen mode Exit fullscreen mode

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:

.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;
}
Enter fullscreen mode Exit fullscreen mode

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:

.button-secondary {
  @extend .button;
  background-color: #4CAF50; // Green
}  
Enter fullscreen mode Exit fullscreen mode

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 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, or using any systematic naming convention for your class names.

See the following HTML:

<button class = "btn btn--red"> Click me! </button>
Enter fullscreen mode Exit fullscreen mode

Typical styling would be something like this:

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

With the & operator we can be much more efficient:

.btn {
  display: inline-block;
  padding: 15px 32px;
  &--red {
    background-color: #ff0000; // Red
  }
  &:hover {
    background-color: #fff; // White
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

@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);
}
Enter fullscreen mode Exit fullscreen mode

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:

@for $i from 1 through 5 {
   .list-#{$i} {
      width: 2px * $i;
   }
}
Enter fullscreen mode Exit fullscreen mode

This will produce the following CSS output:

.list-1 {
  width: 2px; 
}

.list-2 {
  width: 4px; 
}

.list-3 {
  width: 6px; 
}

.list-4 {
  width: 8px; 
}

.list-5 {
  width: 10px; 
}
Enter fullscreen mode Exit fullscreen mode

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:

@for $i from 1 to 5 {
   .list-#{$i} {
      width: 2px * $i;
   }
}
Enter fullscreen mode Exit fullscreen mode

This produces the following CSS:

.list-1 {
  width: 2px; 
}

.list-2 {
  width: 4px; 
}

.list-3 {
  width: 6px; 
}

.list-4 {
  width: 8px; 
}
Enter fullscreen mode Exit fullscreen mode

@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:

$i: 1;
@while $i < 6 {
  .list-#{$i} {       
     width: 2px * $i;   
  }
  $i: $i + 1;
}
Enter fullscreen mode Exit fullscreen mode

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 #{ }.

#{$variable_name}
Enter fullscreen mode Exit fullscreen mode

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

@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);
}
Enter fullscreen mode Exit fullscreen mode

This will compile in CSS as follows:

.block1 {
    background-image: url("img.png");
    position: absolute;
    top: 0px;
    right: 0px;
}

.block2 {
   background-color: lightgray;
   position: absolute;
   top: 0px;
   left: 0px;
}
Enter fullscreen mode Exit fullscreen mode

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:

%placeholder {
    width: 100%;
    height: 100%;
}
body {
    @extend %placeholder;
}
p {
    @extend %placeholder;
}
Enter fullscreen mode Exit fullscreen mode

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

This outputs to CSS as follows:

body, p {
    width: 100%;
    height: 100%;
}
Enter fullscreen mode Exit fullscreen mode

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.

Complete Guide to Freelancing package

Available now at 👉 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. If you'd like to read more of my articles, check them out on my blog.

Thanks for reading 🎉

Top comments (6)

Collapse
 
justatee profile image
Justatee • Edited

If you using DartSass, stop using @import and use @use instead. Reason ? “Sass will gradually phase it out over the next few years, and eventually remove it from the language entirely” from Sass official homepage.

Collapse
 
epsi profile image
E.R. Nurwijayadi

Cool.

I wrote a SASS article long time ago.

epsi-rns.gitlab.io/frontend/2019/0...

SASS loop spacing class

Collapse
 
nicolasomar profile image
Nicolás Omar González Passerino

This is what I call good starting point.

Simple. Clean and with examples.

Thank you for the knowledge

Collapse
 
edwinoaragon profile image
Edwin Aragon

Good article! I had been trying to my team to get into it with no luck til know but someday we will use it!. I was lengthy but easy to digest! Thank you!

Collapse
 
bloolizard profile image
Edwin Villanueva

Good stuff.

Collapse
 
kevin_david_k profile image
Kevin David

When ever I hear SAAS word I thought its Saasland. :P