SASS
Syntactically Awesome Stylesheet
Introduction
- Sass is an extension to CSS
- Sass is a CSS pre-processor
- Sass reduces the repetition of CSS and therefore saves time
- Sass was designed by Hampton Catlin and developed by Natalie Weizenbaum in 2006
- Sass is free to download and use
System Requirements for Sass
- Operating system – Sass is platform independent
- Browser support – Sass works in Edge/IE (from IE 8), Firefox, Chrome, Safari, Opera
- Programming language – Sass is based on Ruby
To install Sass, follow the link https://sass-lang.com/install
Fun Fact: Sass has two syntaxes! The SCSS syntax (.scss)
is used most commonly. It’s a superset of CSS, which means all valid CSS is also valid SCSS. The indented syntax (.sass)
is more unusual: it uses indentation rather than curly braces to nest statements, and newlines instead of semicolons to separate them.
Preprocessing
CSS by itself can be entertaining, but stylesheets are growing bigger, more intricate, and more difficult to manage. A preprocessor can be
useful here. Nesting, mixins, inheritance, and other useful characteristics that Sass provides that CSS doesn’t yet have to make it easier to create solid, stable CSS.
Sass has features that don’t exist in CSS, like nesting, mixins, inheritance, and other nifty goodies that help you write robust, maintainable CSS.
The most direct way to make this happen is in your terminal. Once Sass is installed, you can compile your Sass to CSS using the sass
command. Sass needs to know which file to build from and where to output the CSS. For example, running sass
input.scss
output.scss
from your terminal would take a single Sass file,
and compile that file to input.scss
.output.scss
You can also watch individual files or directories with the —
flag. The watch
the flag tells Sass to watch your source files for changes, and re-compile CSS each time you save your Sass. If you wanted to watch (instead of manually build) your watch
file, you’d just add the watch flag to your command, like so:input.scss
sass --watch input.scss output.css
You can watch and output to directories by using folder paths as your input and output and separating them with a colon. In this example:
sass --watch app/sass:public/stylesheets
Sass would watch all files in the
folder for changes and compile CSS to the app/sass
folder.public/stylesheets
Variables
Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you’ll want to reuse. Sass uses the $
symbol to make something a variable.
Example:
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
When the Sass is processed, it takes the variables we define for the $font-stack
and $primary-color
and outputs normal CSS with our variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site.
Using Sass !global
The default behavior for a variable can be overridden by using the !global
switch. !global
indicates that a variable is global, which means that it is accessible on all levels.
Example:
$myColor: red;
h1 {
$myColor: green !global;
color: $myColor;
}
p {
color: $myColor;
}
In this example, !global
added so it will override the $myColor
red into green.
Nesting
You’ve probably observed when coding HTML that it has a distinct hierarchical and visible structure. CSS, on the other hand, doesn’t. With Sass, you may nest CSS selectors in a way that corresponds to the visual structure of your HTML. Be mindful that having too many nested rules can produce overqualified CSS, which can be difficult to manage and is typically not a good idea. With that in mind, the following is an illustration of various typical styles for a website’s navigation:
// SASSnav { ul { margin: 0; padding: 0; list-style: none; } li { display: inline-block; } a { display: block; padding: 6px 12px; text-decoration: none; } } | // CSSnav ul { margin: 0; padding: 0; list-style: none; } nav li { display: inline-block; } nav a { display: block; padding: 6px 12px; text-decoration: none; } |
The ul, li, and selectors are nestled inside the nav selector, as you’ll see. This is a fantastic approach to organizing and improving the readability of your CSS.
Sass Importing Files
Including the content of one file in another is possible with the @import directive. Due to speed concerns, calling the CSS @import directive more than once results in an additional HTTP request. A separate HTTP call is not necessary at runtime because the Sass @import directive incorporates the file in the CSS!
Sass will understand that you mean a .sass or .scss file without you having to provide the file extension. CSS files can also be imported. Any variables or mixins created in the imported file can then be utilized in the main file once the @import directive imports the file. In the main file, you can import as many files as you need.
Example:
@import "variables";
@import "colors";
@import "demo";
Let’s look at an example: Let’s assume we have a reset file called “demo.scss
“
//demo.scss
html,
body,
ul,
ol {
margin: 0;
padding: 0;
}
and now we want to import the “demo.scss
” file into another file called “standard.scss
“.
//standard.scss
@import "demo";
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
So, when the “standard.css"
the file is transpired and the CSS will look like this:
//CSS output
html, body, ul, ol {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica, sans-serif;
font-size: 18px;
color: red;
}
Partials
Small pieces of CSS can be created as partial Sass files that can be included in other Sass files. This is a fantastic method for organizing your CSS into modules and making things simpler to maintain. A Sass file with a leading underscore is known as a partial.
Sass partial syntax:
_filename;
By using an underscore, Sass is informed that the file is incomplete and shouldn’t be converted into a CSS file. Utilizing the @use rule, Sass partials are employed.
Sass Mixins
- You can write CSS that will be used repeatedly on a website using the @mixin directive.
- You can utilize (include) the mixin by using the @include directive.
// SASS@mixin theme($theme: DarkGray) { background: $theme; box-shadow: 0 0 1px rgba($theme, .25); color: #fff; } .info { @include theme; } .alert { @include theme($theme: DarkRed); } .success { @include theme($theme: DarkGreen); } | // CSS .info { background: DarkGray; box-shadow: 0 0 1px rgba(169, 169, 169, 0.25); color: #fff; } .alert { background: DarkRed; box-shadow: 0 0 1px rgba(139, 0, 0, 0.25); color: #fff; } .success { background: DarkGreen; box-shadow: 0 0 1px rgba(0, 100, 0, 0.25); color: #fff; } |
Using the @mixin directive and giving it a name allows you to build a mixin. Our mixin theme has a name. Additionally, we’re utilizing the variable $theme enclosed in parenthesis so that we may supply any theme we like. Following the creation of your mixin, you can use it as a CSS declaration by beginning the declaration with @include and the name of the mixin.
Extend/Inheritance
A set of CSS properties can be shared from one selector to another with @extend.
/* This CSS will print because %message-shared is extended. */
%message-shared {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
// This CSS won't print because %equal-heights is never extended.
%equal-heights {
display: flex;
flex-wrap: wrap;
}
.message {
@extend %message-shared;
}
.success {
@extend %message-shared;
border-color: green;
}
.error {
@extend %message-shared;
border-color: red;
}
.warning {
@extend %message-shared;
border-color: yellow;
}
The code above instructs .message,.success,.error
and .warning
to act in a manner similar to %message-shared. As a result, everywhere %message-shared appears, .message, .success,.error
& .warning
will as well. Each of these classes will receive the same CSS properties as %message-shared in the generated CSS, which is where the magic happens. This saves you from having to label HTML components with several class names.
In addition to utilizing placeholder classes, Sass allows you to extend the most common simple CSS selectors. However, using placeholders is the simplest way to ensure that you aren’t extending a class that is nested elsewhere in your styles, which may lead to undesired selectors in your CSS.
SASS Functions
SASS String Functions
The string functions are used to work with and extract data from strings. Strings in Sass are 1-based. In a string, the initial character is located at index 1, not 0.
All Sass string functions are listed in the table below:
quote(string) | Adds quotes to string, and returns the result. Example: quote(Hello world!) |
str-index(string, substring) | Returns the index of the first occurrence of the substring within the string. Example: str-index("Hello world!", "H") |
str-insert(string, insert, index) | Returns string with insert inserted at the specified index position. Example: str-insert("Hello world!", " wonderful", 6) |
str-length(string) | Returns the length of the string (in characters). Example: str-length("Hello world!") |
str-slice(string, start, end) | Extracts characters from a string; start at the start and ends at the end, and returns the slice. Example: str-slice("Hello world!", 2, 5) |
to-lower-case(string) | Returns a copy of the string converted to lowercase. Example: to-lower-case("Hello World!") |
to-upper-case(string) | Returns a copy of the string converted to upper case. Example: to-upper-case("Hello World!") |
unique-id() | Returns a unique randomly generated unquoted string (guaranteed to be unique within the current sass session). Example: unique-id() |
unquote(string) | Removes quotes around string (if any), and returns the result. Example: unquote("Hello world!") |
SASS Numeric Functions
Numerical values can be changed using numeric functions.
Some Sass numeric functions are listed in the table below:
abs(number) | Returns the absolute value of a number. Example: abs(15) |
ceil(number) | Round the number up to the nearest integer. Example: ceil(15.20) |
comparable(num1, num2) | Returns whether num1 and num2 are comparable. Example: comparable(15px, 10px) |
floor(number) | Round the number down to the nearest integer. Example: floor(15.80) |
max(number…) | Returns the highest value of several numbers. Example: max(5, 7, 9, 0, -3, -7) |
min(number…) | Returns the lowest value of several numbers. Example: min(5, 7, 9, 0, -3, -7) |
percentage(number) | Converts number to a percentage (multiplies the number by 100). Example: percentage(1.2) |
random() | Returns a random number between 0 and 1. Example: random() |
random(number) | Returns a random integer between 1 and number. Example: random(6) |
round(number) | Round the number to the nearest integer. Example: round(12.20) |
SASS List Function
- Accessing values in a list, combining lists, and adding items to lists are all possible using the list functions.
- Sass lists are unchangeable. Therefore, list functions that return a list will produce a new list rather than alter the original list.
- Lists in Sass are based on 1. In a list, the first item is located at index 1, not 0.
Some Sass numeric functions are listed in the table below:
append(list, value, [separator]) | Adds a single value to the end of the list. The separator can be auto, comma, or space. auto is the default. Example: append((a b c), d) |
index(list, value) | Returns the index position for the value in the list. Example: index(a b c, b) |
is-bracketed(list) | Checks whether the list has square brackets. Example: is-bracketed([a b c]) |
join(list1, list2, [separator, bracketed]) | Appends list2 to the end of the list1. The separator can be auto, comma, or space. auto is the default (will use the separator in the first list). bracketed can be auto, true, or false. auto is the default. Example: join(a b c, d e f) |
length(list) | Returns the length of the list. Example: length(a b c) |
list-separator(list) | Returns the list separator used, as a string. Can be either space or a comma. Example: list-separator(a b c)
|
nth(list, n) | Returns the nth element in the list. Example: nth(a b c, 3)
|
set-nth(list, n, value) | Sets the nth list element to the value specified. Example: set-nth(a b c, 2, x)
|
zip(lists) | Combines lists into a single multidimensional list. Example: zip(1px 2px 3px, solid dashed dotted, red green blue)
|
SASS Map Functions
- The map data type in Sass represents one or more key/value pairs.
- Sass maps are unchangeable. As a result, the map functions that return maps will always produce new maps rather than altering the original maps.
Some Sass map functions are listed in the table below:
map-get(map, key) | Returns the value for the specified key in the map. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px)
|
map-has-key(map, key) | Checks whether the map has the specified key. Returns true or false. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px)
|
map-keys(map) | Returns a list of all keys in a map. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px)
|
map-merge(map1, map2) | Appends map2 to the end of map1. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px)
|
map-remove(map, keys…) | Removes the specified keys from the map. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px) Result: ("normal": 18px) |
map-values(map) | Returns a list of all values in a map. Example: $font-sizes: ("small": 12px, "normal": 18px, "large": 24px)
|