DEV Community

Cover image for Sass Crash Course in a Book
Programming with Shahan
Programming with Shahan

Posted on • Edited on

Sass Crash Course in a Book

sass crash course thumbnail

🤷‍♂️What is Sass

Sass (which stands for Syntactically Awesome Style Sheets) is an extension of CSS that enables you to use things like variables, nested rules, inline imports, and more. It also helps to keep things organized and allows you to create style sheets faster.

The benefit of using Sass is that sass is compatible with all versions of CSS.

Tips: Before continuing, I encourage you to read this full article first and then watch my sass crash course video at bottom of this article which is only 15 minutes longer where I explained the fundamentals of Sass concepts in more detail. This way your Sass memory will remain much longer than usual.

01. 📦Store Data with Sass Variables

One feature of Sass that's different than CSS is it uses variables. They can be declared and set to store data as variables similar to JavaScript.

In JavaScript, variables are declared using let and const keywords. In Sass, variables start with a $ followed by the variable name.

Here is a real example🔻

Let's say we need to use the success color 'green' in different places without repeating its name. So, we need to write code like this:

$success-color: green;
Enter fullscreen mode Exit fullscreen mode

Then we use this global variable in different places like this:

.success {
color: $sucess-color;
}

h3 {
color: $success-color;
}
Enter fullscreen mode Exit fullscreen mode

One example where variables are useful is when a number of elements need to be the same color. If that color is changed, the only place to edit the code is the variable value👌.

02. 🤏Nest CSS with Sass

Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML which is a useful way of organizing a style sheet.

Normally, each element is targeted on a different line to style it, like so👇

Without Nesting:

footer {
background-color: #000;
}

footer ul {
list-style: none;
}

footer ul li {
display: flex;
}
Enter fullscreen mode Exit fullscreen mode

After Nesting:

footer {
  background-color: #000;

  ul {
   list-style: none;

   li {
    display: flex;
   }
  }
}
Enter fullscreen mode Exit fullscreen mode

This is where nesting can help organize your code by placing child style rules within the respective parent elements:

03. 🧣Create Reusable CSS with Mixins

In Sass, a mixin is a group of CSS declarations. So we can reuse them in our style sheet.

As you know newer CSS features take time before they are fully compatible with all browsers. As features are adopted to browsers, CSS rules using them may need vendor prefixes. As an example b*ox-shadow* property.

Without Mixins:

.card {
  -webkit-box-shadow: 0px 0px 4px #fff;
  -moz-box-shadow: 0px 0px 4px #fff;
  -ms-box-shadow: 0px 0px 4px #fff;
   box-shadow: 0px 0px 4px #fff;
}
Enter fullscreen mode Exit fullscreen mode

Imagine, we have different types of cards on our website with different effects of box-shadow. It's a lot of typing to re-write this rule to support all browsers.

This is where Mixins come in. Mixins are like JavaScript functions for CSS. Here is how to write one:

With Mixins:

@mixin box-shadow($x, $y, $blur, $c) {
  -webkit-box-shadow: $x $y $blur $c;
  -moz-box-shadow: $x $y $blur $c;
  -ms-box-shadow: $x $y $blur $c;
   box-shadow: $x $y $blur $c;
}
Enter fullscreen mode Exit fullscreen mode

The definition starts with @mixin followed by a custom name. The parameters (the $x, $y, $blur, and $c in the example above) are optional. Now any time a box-shadow rule is needed, only a single line calling the mixin replaces having to type all the vendor prefixes.

We need to call @mixin with the @include directive. Have a look👇

.card {
  @include box-shadow(0px, 0px, 5px, #000);
}

.popup-card {
  @include box-shadow(2px, 2px, 10px, #000);
}
Enter fullscreen mode Exit fullscreen mode

04. 🔍Use @if and @else to Add Logic To Your Styles

In Sass, @if @else statement is similar to JavaScript. It is very useful in Sass when we search for a specific condition before applying any styles. like so,

@mixin text-color($val) {
  @if $val == danger {
    color: red;
  }
  @else if $val == success {
    color: green;
  }
  @else {
    color: black;
  }
}
Enter fullscreen mode Exit fullscreen mode

Then this is how we need to apply this mixin in different places:

h1 {
 @include text-color(danger);
 font-size: 2rem; // We can add additional properties.
}

.sucess-text {
  @include text-color(success);
  font-weight: bold; // We can add additional properties.
}
Enter fullscreen mode Exit fullscreen mode

05. ➰Sass @Loop

Sass has several loop options, much like other programming languages. They include the @for loop, @each loop, and @while loop. These loops are an incredibly powerful tool for generating CSS code because you can defer code generation into an iterable task.

♾Use @for to Create a Sass Loop:

In Sass, @for is used in two ways: "start through end" or "start to end". The main difference between these two methods is that the "start to end" excludes the end numbers as part of the count, and "start through end" includes the end number as part of the count.

Here is a start through end example:🔻

@for $i from 1 through 5 {
  .text-#{$i} { font-size: 10px * $i; }
}
Enter fullscreen mode Exit fullscreen mode

The #{$i} part is the syntax to combine a variable ( i ) with text to make a string. So, when this Sass file is converted to CSS, it will looks like this:

.text-1 {
  font-size: 10px;
}

.text-2 {
  font-size: 20px;
}

.text-3 {
  font-size: 30px;
}

.text-4 {
  font-size: 40px;
}

.text-5 {
  font-size: 50px;
}
Enter fullscreen mode Exit fullscreen mode

This is why @for is a powerful way to create a very long grid layout or any HTML elements with just one line of code. Now you have 5 different text sizes for your website available as CSS classes.

"start to end" is the same as "start through end". Just remember "start to end" excludes the end number as part of the count.

Start to end example:🔻

@for $j from 1 to 6 {
  .text-#{$j} {font-size: 10px * $j}
}

//The result will look like this:
.text-1 {
  font-size: 10px;
}

.text-2 {
  font-size: 20px;
}

.text-3 {
  font-size: 30px;
}

.text-4 {
  font-size: 40px;
}

.text-5 {
  font-size: 50px;
}

Enter fullscreen mode Exit fullscreen mode

Here you can see the last count (6) is not included in this loop.

🏹Use @each to Map Over Items in a List:

The @each rule makes it easy to emit styles or evaluate code for each element of a list or each pair in a map. Once each iteration, the variable gets assigned to the current value from the list or map.

Have a look without map:

@each $color in red, green, yellow {
  .#{$color}-text {color: $color;}
}
Enter fullscreen mode Exit fullscreen mode

Have a look with Map:

$colors: (color1: red, color2: green, color3: yellow);

@each $key, $color in $colors {
  .#{$color}-text {color: $color;}
}

Enter fullscreen mode Exit fullscreen mode

You can see, the map has slightly different syntax just like JavaScript. So, here the $key variable is needed to reference the keys in the map. If you don't supply $key, the compiled CSS would have color1, color2... and will never touch the actual value.

Both of the above code examples are converted into the following CSS:

.red-text {
  color: red;
}

.green-text {
  color: green;
}

.yellow-text {
  color: yellow;
}
Enter fullscreen mode Exit fullscreen mode

🔐Use @while Until a Condition is Met to Apply a Style:

In Sass, there is no difference with the @while directive compare to JavaScript. It creates CSS rules until a condition is met.

Earlier, we use the @for directive to create repeated tasks without duplication. It can be done with @while.

Have a look:

$i: 1;
@while $i < 6 {
  .text-#{$i} { font-size: 10px * $i;}
   $i: $i + 1;
}
Enter fullscreen mode Exit fullscreen mode

So, first, we take a variable and set it to 1. Next, we check the condition with the @while directive to create different sizes of text while $i is less than 6. Make sure to increment $i by 1 to avoid an infinite loop after setting the CSS rule.

06. 🗳Use _Partial to Split Your Styles into Smaller Chunks

A partial is a Sass file named with a leading underscore, i.e: _partial. scss . The underscore lets Sass know that the specific file is partial and will not be generated into a CSS file. Sass partials are meant to be used with the @import directive. This is a great way to group similar code into a module to it organized.

For example, if all your text color is saved in a separate sass file called "_textColor.scss", and you want them in the main.scss module, this is how to use them in the main Sass file:

@import 'textColor'
Enter fullscreen mode Exit fullscreen mode

Note that you don't need to specify the underscore and file extension in the import statement. Because Sass understands it is a partial. Once a partial is imported into a file, all text color, mixins, and other bunch of code are available to use.

07. 💱Extends One Set of CSS Styles to Another Element

@extend is a feature of Sass that allows classes to share a set of properties with one another.

For example, the below block of CSS rules style .card class. it has some properties like background color, width, height.

.card {
  background-color: #fff;
  width: 200px;
  height: 150px; 
}
Enter fullscreen mode Exit fullscreen mode

Now you want another card called ".popup-card". It has the same properties just like the base ".card" class. But we need additional property in the popup card. It is possible to copy and paste from the base card to the target class. But there is a much better way to do it with the @extend directive.

Have a look:

.popup-card {
  @extend .card;
  border-radius: 5px;
  background-color: #349db;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we can overwrite styles in the base class to the target class by reassigning the values. Otherwise, we will have the same properties as base ".card" as well as our additional styles.

Sass course in a book by shahan

🎥Sass Crash Course In a Book [full tutorial]

Here is the full detail of this article that you just read. Make sure to take notes and play around with your code. Otherwise, things are going to fade away soon. I tried hard to teach fundamentals sass/scss concepts with beautiful visual images so that you can remember them very well.

👏Conclusion

So this is all about Sass concepts that you may come up with. There are other minor concepts that you may need to be familiar with if you needed to. Otherwise learn the fundamentals that you just read from this article. 
Some of these features could be depreciated in the future. So keep an eye on their official sass website to get new updates.

If you like my article and explanation video, make sure to subscribe my YouTube channel.

Feel free to leave a comment and follow me to learn more about programming news.

Social media: Twitter 🦅 / Insta 📷

Thanks for your reading and happy coding :)

Top comments (4)

Collapse
 
supportic profile image
Supportic

@import will get deprecation flag this october and will be deprecated october 2022
github.com/sass/sass/blob/main/acc...

@use and @forward is what you want in future.

Collapse
 
codewithshahan profile image
Programming with Shahan

Thanks for this information.

Collapse
 
sameeravhad119 profile image
sameeravhad119 • Edited

In css also, we can define variables, so it is same feature right ?

Collapse
 
codewithshahan profile image
Programming with Shahan

Yeah