Sass is powerful and you can use variables and mixins to improve your CSS workflow. With variables, you can define values and use them in your code later. Another great feature in Sass is nesting which is another feature that you can use to their advantage. Finally, we will take a look at mixins, To store a value:
Variables
Variables can be used to store CSS values. It’s as simple as that. Let’s take a look at the syntax in SCSS and Sass.
SCSS:
$red: #FF0000;
Sass:
$red: #FF0000
After storing a value, how do you use it? This is how in SCSS:
.foobar { background: $red; }
Here’s the Sass version:
.foobar background: $red
The CSS will turn out like this:
.foobar { background: #ff0000; }
As you can guess, you can use the variable on any selectors or even combine them with other values. Cool, huh?
.foobar { background: #ff0000 repeat-y fixed; }
Nesting
Nesting is simple and powerful, However, make sure that you do not overuse it. You can learn more by reading this nesting guide by the Sass Way.
.foobar { .text { color: $red; } }
The following code will turn into the following CSS:
.foobar .text { color: #ff0000; }
Mixins
Finally, mixins are great for grouping together various rules; for example, you can use mixins to combine vendor prefixes.
SCSS:
@mixin transitions ($transition) { -webkit-transition: $transition; -moz-transition: $transition; -ms-transition: $transition; -o-transition: $transition; transition: $transition; } .box { @include transitions(all 4s ease); }
Sass:
@mixin transitions ($transition) -webkit-transition: $transition -moz-transition: $transition -ms-transition: $transition -o-transition: $transition transition: $transition .box transitions(all 4s ease)
In essence, a mixin is a little bit like passing parameters into a function. You can select an element and then pass in some values and it will apply all of the vendor prefixes to that item.
Now that you understand a little bit more about SASS, on the next post, let’s take a look at how we can organize our code and then import them into our main stylesheet. If you have any questions, feel free to leave a comment below.