Sass/SCSS Concepts (pt. 2)
Part 2 of a quick reference guide to some basic Sass concepts.
Sass comes equipped with built-in modules that contain useful functions. Here are some examples from the sass:color module.
- fade-out takes a number between 0 and 1 and decreases opacity by that amount:
- fade-in changes a color by increasing its opacity:
- adjust-hue changes the hue of a color by taking a color and number of degrees (usually between -360 and 360) and rotating the color wheel by that amount.
Sass also allows us to perform mathematical functions to compute measurements, including colors. For example, we could add two hex colors together:
and Sass would perform the operation on every two digits (referencing the red, green, and blue components), so the resulting color value would be #050709. We could also put in HSLA or string colors such as ‘red’ and ‘blue’.
Sass arithmetic operators include +- * / %. Note that units being operated on must be compatible and cannot be squared, so 10px * 10px would have to be written as 10px * 10.
Also worth noting is that in CSS the / character can be used as a separator, but in Sass it can also be used for division. There are specific instances when / counts as division:
- If the value is stored in a variable or returned by a function.
- If the value is surrounded by parentheses, unless the parentheses are outside a list and the value is inside.
- If the value is used as part of another arithmetic expression.
each loops can be used in Sass to iterate on each value in a list:
for loops can be used to style multiple elements or assign properties all at once:
@if, @else-if and @else conditionals can also be used:
A well-organized Sass file structure should make it easy to think about the function of each component:
The existing CSS @import rule can be used to include other SCSS/Sass files. Typically, all SCSS files are imported into a main SCSS file, which has access to any variables or mixins defined in its imported files. Note the use of partials in the example as well (such as _buttons.scss). Partials use an underscore prefix that tells Sass to hold off on compiling the file individually and instead import it. Make sure to omit the underscore when importing a partial.
@extend can be used to include another class’s properties in a separate class (in addition to its own properties). This makes it easier to maintain HTML code by removing the need to have multiple classes on an element.
%placeholders are used to create classes solely for extending, and only become active once extended somewhere else.
It’s important to note that mixins, unlike extend, insert their code inside the selector’s rules wherever they are included, only creating “original” code if they are assigning a new value via an argument. As a general rule of thumb you should only create mixins when you need to pass in an argument, otherwise use @extend.