SCSS Guide for a beginner (Part 3).

This is the continuation of my previous blogs, in this article we are going to learn about mixins, partials, inheritance and few built-in module functions in SCSS, so let's get started.

Mixins

Many times we write same CSS code in multiple classes which gets really tedious and boring, this problem could be solved with writing mixins, so we will create a flex box mixin which we can use in different components having similar use case.

To create a mixin we use @mixin and to use them in classes we make use of @include keyword followed by mixin_name, we can also specify parameters in the parenthesis.

@mixin flexbox($horizontal:center, $vertical:center){
     display:flex;
     justify-content:$horizontal;
     align-items:$vertical;
}
.d-flex-center{
     @include flexbox;
}
.d-flex-start{
     @include flexbox($horizontal:flex-start,$vertical:flex-start);
}

In the above example.d-flex-center will get default horizontal and vertical values as center because we didn't specify any parameters, similarly for.d-flex-start it will be flex-start. Another use case of mixin that i personally use is while writing media queries, like we have to write media queries quite often and the syntax to write it down is quite tedious so let's see how to do it.

@mixin for-large-screen {
  @media all and (min-width: 600px) {
    @content;
  }
}

.dialog {
  border: 1px solid var(--c-base-200);
  background-color: #fff;
  box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24);
  border-radius: .25rem;
  color: #000;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  max-width: 90vw;
  @include for-large-screen {
    max-width: 40vw;
  }
}

So here this will create a media query for dialog where in for large devices having width greater than 600px would get 40vw width.

Partial

We create Partial files with _(underscore)fileName.scss and write CSS code in it and then import it in different modules with @import keyword. Partial files did not get compiled, and we can use them to CSS code DRY.

//_colors.scss

$myPink: #EE82EE;
$myBlue: #4169E1;
$myGreen: #8FBC8F; 

//styles.scss
@import "colors";

body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: $myBlue;
}

Built In Modules

With the latest Dart release of SASS they've introduced a bunch of built-in modules which have rich sass features, there are several built in modules such as color, list, math, string, map and selector. some of the helpful features are

@use 'sass:math';
$half: math.percentage(1/2);

@use 'sass:color';
color.adjust(#6b717f, $red: 15); // #7a717f
color.complement(#036); // #663300

explore more about built in modules

So that's it, thank you for a read!