DEV Community

Cover image for SASS IT! The Beginner's Guide to SASS
Tabassum Khanum
Tabassum Khanum

Posted on

SASS IT! The Beginner's Guide to SASS

Are CSS Preprocessors necessary? My answer is yes and also no. You may not need a preprocessor for small web projects or applications. For bigger projects with complex user interfaces, preprocess helps a lot as maintenance & readability of CSS code get harder as the project gets bigger.

gif

For those who don't know what preprocessors are, they’re all fantastic tools to maintain your CSS, especially when working with large codebases.

"A CSS preprocessor is a program that lets you generate CSS from the preprocessor’s own unique syntax. There are many CSS preprocessors to choose from, however, most CSS preprocessors will add some features that don’t exist in pure CSS, such as mixin, nesting selector, inheritance selector, and so on. These features make the CSS structure more readable and easier to maintain."
— MDN

And Sass (Syntactically Awesome Style Sheets) is a CSS preprocessor that gives your CSS superpowers. It has a couple of functionalities that you can use to make your CSS neat and reusable such as variables, nested rulings, mixins, functions, and much more.

The Big Question - WHY do we need SASS/preprocessor?

  1. It makes our Code DRY.
  2. Can avoid endless CSS lines by using classes, variables, etc.
  3. Clean code, with variables and reusable components.
  4. Ability to implement logic and calculation.
  5. Sass gets compiled into CSS and adds all the necessary vendor prefixes so you don't have to worry about manually writing them out.

Reasons to Use SASS in Your Project

Variables

In JavaScript, variables are defined using the let and const keywords. In Sass, variables start with a $ followed by the variable name to store the data.
The benefit here is that if that value changes, you simply need to update a single line of code.

$main-fonts: Arial, sans-serif;
$headings-color: green;

h1 {
  font-family: $main-fonts;
  color: $headings-color;
}
Enter fullscreen mode Exit fullscreen mode

Nesting

SASS made it possible by taking care of nesting CSS classes or selectors inside of it and generate CSS under the hood. This is useful especially if you’re following the BEM Architecture as SASS is very compatible with its architecture and they mentioned it frequently in their docs so to speak.

For a large project, the CSS file will have many lines and rules. This is where nesting can help organize your code by placing child-style rules within the respective parent elements:

nav {
  background-color: red;

  ul {
    list-style: none;

    li {
      display: inline-block;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Mixins

Another major issue with CSS is that you'll often use a similar group of styles. Mixins allow you to encapsulate a group of styles, and apply those styles anywhere in your code using the @include keyword.

An example of when you'd use mixins is when using Flexbox.

@mixin flex-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-direction: column;
  background: #ccc;
}

.card {
  @include flex-container;
}

.aside {
  @include flex-container;
}
Enter fullscreen mode Exit fullscreen mode

@if and @else to Add Logic

The @if, @else if, and @else directives in Sass are useful to test for a specific case - they work just like the if, else if and else statements in JavaScript.

@mixin text-effect($val) {
  @if $val == danger {
    color: red;
  }
  @else if $val == alert {
    color: yellow;
  }
  @else if $val == success {
    color: green;
  }
  @else {
    color: black;
  }
}
Enter fullscreen mode Exit fullscreen mode

@for @each and @while in SASS

@for is used in two ways: "start through end" or "start to end". The main difference is that the "start to end" excludes the end number as part of the count, and "start through end" includes the end number as part of the count.

@for $i from 1 through 12 {
  .col-#{$i} { width: 100%/12 * $i; }
}
Enter fullscreen mode Exit fullscreen mode

the @each directive which loops over each item in a list or map. On each iteration, the variable gets assigned to the current value from the list or map.

colors: (color1: blue, color2: red, color3: green);

@each $key, $color in $colors {
  .#{$color}-text {color: $color;}
}
Enter fullscreen mode Exit fullscreen mode

The @while directive is an option with similar functionality to the JavaScript while loop. It creates CSS rules until a condition is met.

$x: 1;
@while $x < 13 {
  .col-#{$x} { width: 100%/12 * $x;}
  $x: $x + 1;
}
Enter fullscreen mode Exit fullscreen mode

Import

We can cut our huge CSS files into smaller pieces with Sass import feature. It is much easier to read & maintain smaller files rather than one big file with endless lines.

Partials in Sass are separate files that hold segments of CSS code. These are imported and used in other Sass files. This is a great way to group similar code into a module to keep it organized.

Names for partials start with the underscore (_) character, which tells Sass it is a small segment of CSS and not to convert it into a CSS file. Also, Sass files end with the .scss file extension. To bring the code in the partial into another Sass file, use the @import directive.

// Your main Sass file
@import 'file';
@import 'anotherFile';
.class {
  // Your code
}
Enter fullscreen mode Exit fullscreen mode

Actually, CSS also has now an import feature. But it works differently. CSS sends an HTTP request to server each time to import a file. Sass does it without an HTTP request, which is a faster approach.

Extend

Sass has a feature called extend that makes it easy to borrow the CSS rules from one element and build upon them in another.

.panel{
  background-color: red;
  height: 70px;
  border: 2px solid green;
}
Enter fullscreen mode Exit fullscreen mode
.big-panel{
  @extend .panel;
  width: 150px;
  font-size: 2em;
}
Enter fullscreen mode Exit fullscreen mode

Sass functions and Operators

Sass offers built-in functions that enable us to do calculations and operations that return a specific value.

They range from color calculations to math operations like getting random numbers and calculation of sizes, and even conditionals.

It also provides support for mathematical operators like +, -, \, *, /, and %, which we can use with the calc function.

@function pxToRem($pxValue) {
  $remValue: ($pxValue / 16) + rem;
  @return $remValue;
}

div {
  width: pxToRem(480);
}
Enter fullscreen mode Exit fullscreen mode
@use "sass:math";

@function pxToRem($pxValue) {
  @return math.div($pxValue, 16px) * 1rem;
}

div {
  width: pxToRem(480px); // gives 30rem
}
Enter fullscreen mode Exit fullscreen mode

Parent Selector

In the Sass code above, you might notice the ampersand symbol & used with the hover pseudo-class. This is called a Parent Selector.

In SASS can nest a couple of selectors by concatenating CSS selectors inside angled brackets({}) using ampersand(&). If you’re using BEM Architecture, you have saved a couple of times tediously typing CSS classes and selectors just to follow the architecture because SASS generates an appropriate CSS under the hood.

<button class="btn btn--red">Click me!</button>
Enter fullscreen mode Exit fullscreen mode
.btn {
  display: inline-block;
  padding: 5px 8px;
  &--red {
    background-color: #ff0000; // Red
  }
  &:hover {
    background-color: #fff; // White
  }
}
Enter fullscreen mode Exit fullscreen mode

Wrap Up

gif2

SASS is a great addition to your workflow as a Front-End Developer which I find really powerful and useful to work with. We have covered quite a lot of features of SASS here but please check out the following resources for a better understanding:

  1. Installing Sass
  2. Setup Sass as VS Code Extension
  3. Practice Sass using Online Editor
  4. Learn Sass
  5. Official Documentation

If you have any questions, feel free to contact me at https://twitter.com/codewithtee!
Thank you very much for reading & till next time🐋

HAPPY CODING🌼

gif3

Top comments (0)