SCSS Guide for a beginner (Part 2).

This is the continuation of my previous blog, in this article we are going to learn about loops, operators and functions in SCSS, so let's get started.

Loops

Loops are basically a sequence of instructions that are performed until a certain condition is reached, so like every other programming language SCSS has while loop, for loop and each loop. So let's understand them with an example, we will create a bunch of custom CSS properties with help of different loops.

We will create utility classes for font weights with help of for loop

@for $i from 1 through 7 {
  .fw-#{$i}00 {
    font-weight: #{$i}00;
  }
}
css:

.fw-100 {
  font-weight: 100;
}, .fw-200, .fw-300 and so on.

So this is a color variable having different shades 100,200 and 300 we will create CSS custom props to use them in stylesheets with help of nested for each loop.

$colors: (
  primary: (
    100: hsla(195, 54%, 78%, 1),
    200: hsl(212, 84%, 61%),
    300: hsl(205, 98%, 20%),
  ),
  secondary: (
    100: hsl(62, 98%, 46%),
    200: hsl(67, 58%, 14%),
    300: hsl(69, 11%, 25%),
  ),
);
@each $type, $shades in $colors {
# this loop will iterate over each color in colors
    @each $shade, $value in $shades {
# this will iterate over shade in the color
      --c-#{$type}-#{$shade}: #{$value};
    }
  }
css:
--c-primary-100: #a9d6e5;
--c-primary-200: #4896ef;
--c-primary-300: #013b65;
--c-secondary-100: #ffe16b;
--c-secondary-200: #ffe600;
--c-secondary-300: #ffb700;

Functions and Operators

SCSS also supports functions and mathematical operators, doing math in CSS is very helpful. Sass has a handful of standard math operators like +, -, *, /, and %. So we will create utility classes for padding and margin with help of functions, operators and loops.

$spacer: .25rem;
@function get-p($size) {
#we are using * operator which will multiply $spacer to current size
    @return $spacer * $size;
}

@for $i from 0 through 7 {
  .p-#{$i} {
    padding:  #{get-p($i)};
  }
 .m-#{$i} {
    margin:  #{get-p($i)};
  }
 }
css => 
.p-0{
padding:0;
}
.m-0{
margin:0;
}
.p-1{
padding:0.25rem;
}
.m-1{
margin:0.25rem;
} 
and so on till .m-7 .

So this is how you can create utility classes, custom props and lot more things with the help of functions, operator and loops. Thank you for reading.