Sass Tutorial menu

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 .css files
  • Sass is free and open source, and the main version today is Dart Sass

How Sass Works

  1. You write styles in a .scss file
  2. The Sass compiler reads the file
  3. It writes a normal .css file
  4. Your HTML page links to that .css file, 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 CSSUses indentation instead of brackets
Every valid CSS file is also valid SCSSLooks very different from CSS
Used by almost everyone todayRarely used

SCSS:

Example

scss
.alert {
  padding: 12px;
  color: darkred;
}

The same thing in the indented syntax:

Example

sass
.alert
  padding: 12px
  color: darkred

This 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

scss
$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:

Output
.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?

Learn Sass with a teacher

Join the Web Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp