Sass Introduction
Sass is a CSS preprocessor: a language that adds extra features to CSS and is then converted into plain CSS.
What is Sass?
- Sass stands for Syntactically Awesome Style Sheets
- It adds features that plain CSS did not have for a long time: variables, nesting, mixins, functions and modules
- Browsers do not read Sass. A compiler converts your Sass files to
.cssfiles - Sass is free and open source, and the main version today is Dart Sass
How Sass Works
- You write styles in a
.scssfile - The Sass compiler reads the file
- It writes a normal
.cssfile - Your HTML page links to that
.cssfile, as usual
The browser never sees the Sass code. It only sees the CSS output.
Two Syntaxes: SCSS and Sass
Sass can be written in two ways.
SCSS (.scss) | Indented syntax (.sass) |
|---|---|
| Uses curly brackets and semicolons, like CSS | Uses indentation instead of brackets |
| Every valid CSS file is also valid SCSS | Looks very different from CSS |
| Used by almost everyone today | Rarely used |
SCSS:
Example
.alert {
padding: 12px;
color: darkred;
}The same thing in the indented syntax:
Example
.alert
padding: 12px
color: darkredThis tutorial uses SCSS, because it is the most popular and easiest to learn when you already know CSS.
A First Look
Here, Ali keeps his shop's brand colour in a variable and nests the hover style inside the button rule.
Example
$shop-green: #15803d;
.order-button {
background-color: $shop-green;
color: white;
padding: 10px 20px;
&:hover {
background-color: black;
}
}
.price {
color: $shop-green;
font-weight: bold;
}The compiler turns it into this CSS:
.order-button {
background-color: #15803d;
color: white;
padding: 10px 20px;
}
.order-button:hover {
background-color: black;
}
.price {
color: #15803d;
font-weight: bold;
}If the shop changes its brand colour, Ali changes one line, and every place that uses $shop-green updates.
Sass and Modern CSS
Modern CSS now has custom properties (--brand: green) and even native nesting. Sass is still widely used because it also gives you mixins, loops, functions and modules, and because big projects and frameworks like Bootstrap are built with it.
Sass and CSS custom properties work well together. Use Sass variables for values you set while building, and CSS custom properties for values that change in the browser, like a dark mode colour.
Exercise
Exercise
Which Sass syntax uses curly brackets and semicolons, just like CSS?
