Have you ever wondered what Sass is? Or maybe you know what it is but have not really taken time to learn and use it? Or you might just want to remind yourself of what you already know. In any case, this article is for you.
If you are a frontend developer, you know that CSS can be fun, but as your stylesheets get larger, they get harder to maintain and organize. That’s where CSS preprocessor come in to save the day.
It add a new layer of awesome on top of a syntax we already know and love. The biggest advantage of using CSS preprocessor is in not having to repeat yourself.
There are many CSS preprocessor out there, but in this article we will be focusing on Sass. It’s one of the most popular preprocessor in use today. Sass empowers frontend developers to advance their frontend skills with unique features that extend CSS capabilities.
Today we will walk you through a beginner’s intro to Sass and its variable to get you familiar with this game-changing tool. Are you ready ? Okey! then let’s ride!
What is Sass?
Sass is an acronym that stands for “Syntactically Awesome Style Sheets” and it is an extension to CSS which helps us write more flexible styles – in other words, it’s a CSS preprocessor.
Sass is a stylesheet language that is an extension of CSS.
CSS are getting larger, more complex, and harder to maintain. This is where a preprocessor can help. Sass can helps us make larger and complicated stylesheets clearer to understand and easier to maintain.
Thanks to features like variables, mixins, nesting, inheritance and many others. The code is more organized which allowing us to work quicker.
How does Sass work?
As we mentioned earlier, Sass is a preprocessor. It takes Sass (.sass
) or SCSS (.scss
) files as input, and outputs CSS files (.css
). Sass adds a lot of great features that can help to create better stylesheets, but as you know, web browsers only understand CSS, not Sass.
“Sass” is never uppercase, no matter whether we are talking about the language or the syntax. Meanwhile, “SCSS” is always uppercase.
What we do is write our CSS (with as much a sprinkling of Sass as needed) in .scss
or .sass
files in our code editor, and then have Sass compile that into a .css
file for the browser to read.
This process is called transpiling. So, you need to give a transpiler some Sass code and then get some CSS code back.
🤔 .scss or .sass any difference?
In Sass there are two ways of writing – .scss
and .sass
– however after being compiled they generate similar output.
.scss
is the modern standard which sometimes called as Sassy CSS. It’s syntax is very similar to CSS in that it uses brackets and semi-colons. Even normal CSS is valid in this syntax.
.sass
is an older syntax that focuses on indentation to separate code blocks and newline characters to separate rules.
By mastering Sass, you will be able to create effortless and beautiful websites with a sleek professional look.
How to setup Sass development environment?
Before we go forward, you need to setup Sass dev environment. Actually, it is pretty easy to setup. In our previous article we have gone through the step by step guide to setup the dev environment in VS Code for Sass.
We are not going to cover the whole dev environment setup process here. So that, kindly follow the following link which will walk you through the entire process.
How to setup and use Sass in VS Code (Dart SASS support + Live page preview)
Once you are ready then jump straight to experiment Sass variables.
Sass in CSS: Feature that extend your vanilla CSS
So far we have setup our dev environment as well as learn basic definitions and different file extensions provided by Sass. It all sounds great, right? So, what can Sass do for your CSS specifically?
Let’s discuss the most notable feature of Sass that extend your vanilla CSS code. Yes! we are talking about Sass variables.
Sass variables
Variables are a way to store information that you can reuse later throughout your stylesheet.
This is especially handy for colors: one can avoid having countless hues of the same color after a long time spent working on a project.
Variables can also be helpful for storing other types of content such as font lists, maps of breakpoints, and default asset paths—presumably anything that you may want to use multiple times across the stylesheet, particularly those that could be updated at a later point.
💡 Note
With Sass, you can store following information in a variable:
• String of text, with and without quotes (e.g. "Sunil"
, 'Sunil'
, Sunil
)
• Numbers (e.g. 2.9
, 95
, 80px
)
• Colors (e.g. blue
, #04a3f9
, rgba (255, 0, 0, 0.5)
)
• Booleans (e.g. true
, false
)
• List of values, separated by spaces or commas (e.g. Helvetica, Arial, sans-serif)
• Nulls (e.g. null
)
• Maps from one value to another (e.g. (key1: value1, key2: value2))
• Function references
As we have mentioned, variables are reusable and thus makes your code easy to maintain and change as per the clients requirement in a small time.
A variable in Sass always starts with a dollar sign ($
), whether you are using it for assignment or retrieval. Directly next to the dollar sign comes the variable name, which is usually made of latin characters, numbers and dashes, or underscores.
Let’s take a look at the syntax for defining variable in Sass:
Syntax:
$variable-name: variable value;
For assignment, the variable name and its value are separated with a colon. Finally, a semicolon ends the statement.
Let’s take an example where we define a color as a variable.
$color-primary: #20639b; // Variable assignment body { background-color: $color-primary; // Variable usage }
💡 Note
Sass supports both single-line and multi-line comments i.e. //
and /* */
. But once the Sass file is compiled into CSS then the resulting CSS will only preserve the multiline comments not the single-line comments, because CSS doesn’t support single-line comments.
Now the background-color
is blue, and when you save the file in VS Code it generates the following CSS code.
body { background-color: #20639b; }
Output on Chrome:
💡 Dashes + Underscores = Same
Dashes and underscores are considered the strict equivalent in Sass variable names; hence, $my-variable
and $my_variable
actually refer to the same location.
You could use one to assign the value and the other to retrieve it, and it will work seamlessly. What’s important to remember is that the dash or underscore is a matter of preference, not syntax.
This is just a basic approach for using variables. You can do a lot more advanced stuff with variables. So let’s learn how scope of a Sass variable works.
Scope of Sass variables
Variables can be defined absolutely anywhere in a stylesheet: at root level, within CSS rule sets, within mixins, within functions, within @media
and @supports
blocks—everywhere.
Depending on where a variable is assigned, however, its access might be restricted to a specific code block; this is what we usually call a scope.
The scope of a variable simply means where a variable is available for use.
The scope of a variable simply means where a variable is available for use. In Sass, we have two type of scopes: Global scope and Local scope.
If a variable has a global scope, it means it is available for use everywhere. A local scope is bounded by {}
. So if a variable is declared within a {}
and thus has a local scope, it is only available for use within that scope.
To understand how scope works, let’s take an example,
$width: 30px; // define the variable .button { $fontSize: 16px; font-size: $fontSize; width: $width; } .dropdown { width: $width; }
Save the file in VS Code which generates the following CSS code.
.button { font-size: 16px; width: 30px; } .dropdown { width: 30px; }
Which of these variables have global scope? Did you say $width
? If you did, you are correct. That is why it is available to both the .button
and .dropdown
class.
The $fontSize
variable on the other hand, has a local scope. It is only available within button and any other selector nested within it. If we try to use $fontSize
in dropdown, you will get an error.
One more thing to remember, local variable take precedence over global variable. So in our example above, let’s re-declare $width
within .dropdown
class, what will the width of the dropdown be? Let’s find out.
$width: 30px; // define the variable .dropdown { // re-defining the variable $width: 50px; width: $width; }
This will be in CSS:
.dropdown { width: 50px; }
So that explains it. The width becomes that of its local scope.
Sass handles scopes the way you would expect it to: a variable defined in a mixin, function, or rule set is local by default. This means that a global variable and a local variable can share the same name seamlessly. This is referred to as variable shadowing in Sass.
The local will be restricted to its own scope, while the global will be accessible elsewhere in the document.
When declaring in an inner scope (such as a function or rule set) a variable whose name already exists in the global namespace, the local variable is said to be shadowing the global one:
$padding: 10px; .module { $padding: 20px; padding: $padding; // 20px } .foo { padding: $padding; // 10px }
In this case, there is a global variable called $padding
with a value of 10px
. Within the .module { }
rule set (scope), a local variable also named $padding
is created with a value of 20px
.
Within the scope, the value of $padding
is now 20px
, but anywhere else in the document, it still refers to the global value, 10px
. Thus, this code snippet will be compiled to:
.module { padding: 20px; } .foo { padding: 10px; }
The !global flag
It is possible to make variable that are declared locally to have a global scope. We use the !global
flag to achieve this.
Let’s go back to our earlier example and try to use a variable declared in .button
in .dropdown
but this time with a !global
flag.
To definitely override a global variable from a local scope, we use the
!global
flag. By definitely, we mean that the variable is not shadowed but effectively replaced by a new value.
$width: 30px; $fontSize: 12px; // define the variable .button { // re-defining the variable $fontSize: 16px !global; font-size: $fontSize; width: $width; } .dropdown { font-size: $fontSize; width: $width; }
This will be in CSS:
.button { font-size: 16px; width: 30px; } .dropdown { font-size: 16px; width: 30px; }
No error was returned this time.
The !global
flag just made $fontSize
available for use everywhere.
💡 Pro Tip
Global variables should be defined outside any rules. It could be wise to define all global variables in its own file, named _globals.scss
, and include the file with the @include
keyword.
As you can see in the code above, using the !global
flag we can change the value for the variable for the entire stylesheet.
While it might be tempting to use the !global
flag when defining a variable at the root of a document, it is probably wiser to omit it.
Indeed, this is an abuse of !global
that might make the code confusing.
Last but not least when it comes to variable assignment there’s a mechanism that makes it possible to assign a variable if it doesn’t have a value yet—the !default
flag:
Then let’s see it next.
The !default flag
When the !default
flag is used for assigning a variable, we are simply saying that if this variable is not assigned elsewhere, make use of this value. It makes a value to act as a fallback.
This can come in handy if we are creating custom variable that will be reused. Let’s see an example.
$padding: 10px; $padding: 20px !default; .foo { padding: $padding; // 10px }
So if this variables don’t get re-assigned elsewhere, these default values will be used.
The !default
flag is incredibly useful when building third-party libraries and modules. It enables users to configure the library, but still provide defaults if they don’t:
// Your configuration of the third party library $third-party-output-prefix: false; // The third party library has some default values such as // $third-party-output-prefix: true !default; // In this case, the value is `false` thanks to `!default`. @import 'third-party-library';
The !default
flag also comes in handy when dealing with dynamically created Sass files from user input, such as theme files:
// User theme stylesheet containing: // $brand-color: hotpink; @import 'user-theme'; // Default configuration $brand-color: grey !default; .foo { color: $brand-color; // hotpink }
Bear in mind that variables with null
value are treated as unassigned by default, which means that a variable assignment with !default
will override a variable assignment to null
:
$padding: null; $padding: 20px !default; .foo { padding: $padding; // 20px }
There’s a lot that can be done with Sass variables such as interpolation. The more you use them, the more you see their uses.
Conclusion
Here we are going to end Sass variables introduction. In a nutshell, Sass is a stylesheet language that is an extension of CSS whereas Sass variables are a way to store information that you can reuse later throughout your stylesheet.
Sass variables have two type of scopes: Global and Local scope. We can also tweak Sass variables through !global
and !default
flag. But we can do so much with Sass variables, hence our next article based on Sass interpolation.
Got any question or addition? Leave a comment. Thank you for reading.
Add comment