DEV Community

Cover image for CSS Pre Processors- SASS
Vishal Sharma
Vishal Sharma

Posted on • Originally published at codeentity.tech on

CSS Pre Processors- SASS

CSS preprocessors are tools that allow you to write more efficient and maintainable CSS code. They extend the capabilities of plain CSS by adding features such as variables, mixins, and functions, which can help you write more modular and scalable stylesheets.

There are several popular CSS preprocessors available, including Sass, Less, and Stylus. In this blog, we’ll take a look at Sass and provide some examples of how it can be used to make your CSS more efficient and maintainable.

What is Sass?

Sass (short for Syntactically Awesome Stylesheets) is a CSS preprocessor that adds features such as variables, mixins, and functions to CSS. It is written in Ruby, but can be used with any project regardless of the programming language being used. Sass files have a .scss extension and are compiled into regular CSS files that can be used in any web project.

Why use Sass?

There are several benefits to using Sass in your web projects:

  • Maintainability

Sass allows you to use variables and mixins, which can make your CSS code more maintainable by allowing you to define styles in a single place and reuse them throughout your stylesheets. This can help reduce duplication and make it easier to update your styles in the future.

  • Modularity

Sass allows you to use import statements to split your stylesheets into smaller, more manageable files. This can make it easier to organize your code and keep your stylesheets organized and easy to read.

  • Functionality

Sass adds features such as functions and operators, which can help you write more efficient and powerful stylesheets. For example, you can use functions to perform calculations and generate styles dynamically, or use operators to concatenate strings or perform other operations.

How to use Sass

To use Sass in your project, you’ll need to install a Sass compiler. There are several options available, including the command-line sass compiler, preprocessor plugins for popular text editors, and compilers like dart-sass to integrate with build tools like webpack.

Once you have a Sass compiler installed, you can start using Sass in your project by creating .scss files and using the @import directive to include them in your main stylesheet.

Here’s an example of how you might use Sass in a project (We will be using scss syntax in this blog to write sass code):

// Define a variable for the primary color
$primary-color: #333;

// Define a mixin for reusable styles
@mixin border-radius($radius) {
  -webkit-border-radius: $radius;
  -moz-border-radius: $radius;
  -ms-border-radius: $radius;
  border-radius: $radius;
}

// Use the mixin and the variable in your styles
.btn {
  background-color: $primary-color;
  @include border-radius(5px);
}
// when this Sass code is compiled, it will output the following CSS:
.btn {
  background-color: #333;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  -ms-border-radius: 5px;
  border-radius: 5px;
}
Enter fullscreen mode Exit fullscreen mode

As you can see, Sass allows you to use variables and mixins to make your CSS more maintainable and efficient. There are many more features available in Sass, including functions, operators, and control directives such as @if, @else, @while, @for, @each.

Conditional Execution @if

As you’d expect, the Sass @if directive and its companions @else if and @else, allow you to include Sass code in the CSS output only if certain conditions are met. The basic syntax is simple:

$age: 27;

.bg-color {
  @if $age < 18 {
    background-color: red;
  } @else if $test == 18 {
    background-color: blue;
  } @else {
    background-color: green;
  }
}
// when this Sass code is compiled, it will output the following CSS:
.bg-color {
  background-color: green;
}
Enter fullscreen mode Exit fullscreen mode

Conditional Looping - @while

As its name implies, the @while directive will continue to output CSS produced by the statements while the condition returns true.

$font-size: 1;

@while $font-size < 4 {
  .font-size-#{$font-size} {
    font-size: #{$font-size}rem;
  }
  $font-size: $font-size + 1;
}
// when this Sass code is compiled, it will output the following CSS:
.font-size-1 {
  font-size: 1rem;
}
.font-size-2 {
  font-size: 2rem;
}
.font-size-3 {
  font-size: 3rem;
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Heads up! Although@while is necessary for a few particularly complex stylesheets, you’re usually better of using either @each or @for if either of them will work. They’re clearer for the reader, and often faster to compile as well.

Unconditional Looping @for

You can use the @for directive to execute a group of statement a specific number of times. It has two variations. The first, which uses the through keyword, executes the statements from to , inclusive and replacing the through keyword with to makes the loop exclusive, that is, it will not be executed when the variable is equal to :

@for $i from 1 through 4 {
  .font-size-#{$i} {
    font-size: #{$i}rem;
  }
}
// when this Sass code is compiled, it will output the following CSS:
.font-size-1 {
  font-size: 1rem;
}
.font-size-2 {
  font-size: 2rem;
}
.font-size-3 {
  font-size: 3rem;
}
.font-size-4 {
  font-size: 4rem;
}

@for $i from 1 to 4 {
  .font-size-#{$i} {
    width: 2px * $i;
  }
}
// when this Sass code is compiled, it will output the following CSS:
.font-size-1 {
  font-size: 1rem;
}
.font-size-2 {
  font-size: 2rem;
}
.font-size-3 {
  font-size: 3rem;
}
Enter fullscreen mode Exit fullscreen mode

Map through list or map @each

Finally, the @each directive will execute a set of items in either a list or a map. For such a powerful structure, the syntax is quite straightforward:

//List
$align: (left, right, center);
@each $direction in $align {
  .text-#{$direction} {
    text-align: $direction;
  }
}
// when this Sass code is compiled, it will output the following CSS:
.text-left {
  text-align: left;
}

.text-right {
  text-align: right;
}

.text-center {
  text-align: center;
}

//Map
$font-map: (
  xs: 12px,
  sm: 14px,
  md: 16px,
  lg: 18px,
  xl: 24px,
);

@each $key, $value in $font-map {
  .text-#{$key} {
    font-size: $value;
  }
}

// when this Sass code is compiled, it will output the following CSS:
.text-xs {
  font-size: 12px;
}

.text-sm {
  font-size: 14px;
}

.text-md {
  font-size: 16px;
}

.text-lg {
  font-size: 18px;
}

.text-xl {
  font-size: 24px;
}
Enter fullscreen mode Exit fullscreen mode

Functions & Mixins

SCSS also supports functions and mixins.

Functions

Functions allow you to perform operations on values and return a result. For example, you can use the darken function to reduce the lightness of a color by a given percentage:

color: darken(#ff0000, 20%);
Enter fullscreen mode Exit fullscreen mode

SCSS also have a number of built-in modules with functions for working with values and styles. Here are some examples of the types of functions that are available in SCSS:

  • color module. Some functions from color module are:

    • rgb(): The rgb() function allows you to specify a color using the red, green, and blue channels.
    • opacify(): The opacify() function increases the opacity of a color.
    • transparentize(): The transparentize() function decreases the opacity of a color.
    • lighten(): The lighten() function increases the lightness of a color by a given percentage.
    • darken(): The darken() function decreases the lightness of a color by a given percentage.
    • saturate(): The saturate() function increases the saturation of a color by a given percentage.
    • desaturate(): The desaturate() function decreases the saturation of a color by a given percentage.
    • grayscale(): The grayscale() function converts a color to grayscale.
    • complement(): The complement() function returns the complement of a color.
  • math module. Some functions from math module are:

    • abs(): The abs() function returns the absolute value of a number. width: abs(-100px); // 100px
    • ceil(): The ceil() function returns the smallest integer that is greater than or equal to a number. width: ceil(99.5px); // 100px
    • floor(): The floor() function returns the largest integer that is less than or equal to a number. width: floor(99.5px); // 99px
    • max(): The max() function returns the maximum value in a list of numbers. width: max(100px, 200px, 300px); // 300px
    • min(): The min() function returns the minimum value in a list of numbers. width: min(100px, 200px, 300px); // 100px
    • percentage(): The percentage() function converts a number to a percentage. width:percentage(math.div(100px, 50px)); // 200%
  • string module. Some functions from string module are:

    • unquote(): The unquote() function removes quotes from a string.
    • quote(): The quote() function adds quotes to a string.
    • str-length(): The str-length() function returns the length of a string. width: str-length("Hello, world!"); // 13
    • to-upper-case(): The to-upper-case() function converts a string to uppercase.
    • to-lower-case(): The to-lower-case() function converts a string to lowercase.
  • list module. Some functions from list module are:

    • length(): The length() function returns the length of a list.
    $list: 1px 2px 3px;
    width: length($list); // 3
    
    • nth(): The nth() function returns the nth element of a list.
    $list: 1px 2px 3px;
    width: nth($list, 2); // 2px
    
    • join(): The join() function concatenates two lists.

      $list1: 1px 2px;
      $list2: 3px 4px;
      width: join($list1, $list2); // 1px 2px 3px 4px
      
    • append(): The append() function adds an element to the end of a list.

    $list: 1px 2px;
    width: append($list, 3px); // 1px 2px 3px
    
  • map module. Some functions from map module are:

    • map-get(): The map-get() function retrieves the value for a given key in a map.
    • map-merge(): The map-merge() function merges two maps together. If the maps have overlapping keys, the values from the second map will overwrite the values from the first map.
    • map-remove(): The map-remove() function removes a key-value pair from a map.

Mixins

Mixins, on the other hand, allow you to define a set of styles that can be reused throughout your stylesheet. For example, you might define a mixin for a common button style:

@mixin button {
  font-size: 16px;
  color: #fff;
  background-color: #000;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

You can then use the mixin in your stylesheet by including it using the @include directive:

.btn {
  @include button;
}
Enter fullscreen mode Exit fullscreen mode

Mixins can also accept arguments, allowing you to customize the styles that are included. For example:

@mixin button($color) {
  font-size: 16px;
  color: #fff;
  background-color: $color;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.btn {
  @include button(#000);
}
Enter fullscreen mode Exit fullscreen mode

Overall, functions and mixins are powerful features of SCSS that allow you to write more efficient and maintainable stylesheets. By using these features, you can write code that is easier to read and understand, and that can be easily reused throughout your application.

Top comments (0)