What is scss mixin? How to create it?

We frontend developers do most html css coding while coding in general. When coding, instead of writing repeated structures over and over again, we prepare them as a component structure and include them in the coding, that is, we do the inclusion process. We usually use sass or scss tools when coding css. Within these tools, there is a mixin structure, a structure where we can create repeated structures.

What is scss mixin?

When css coding, we repeat a lot of coding, for example, we use the following codes to combine objects in a box in the middle.

.box {
  display: flex;
  justify-content: center;
  align-items: center;
}

Creating a mixin called BoxCenter and including it when we need to create these codes will make our job a little easier than rewriting these codes many times. In addition, it will minimize the time we lose in writing the same codes.

What is the structure of a scss mixin and how to create it?

Mixin Structure and Creation

Creating and using mixin in scss is actually very simple. If a function is created in a programming language, a mixin structure can be created in a similar structure in scss.

@mixin isim(parameter or parameters){
   // Css Code
}

You can create a mix with or without parameters. This is completely up to you. I will be explaining both uses.

Creating and using a mix without parameters

We create a mixin called BoxCenter. Then we include the mixin we created ” @inculude BoxCenter() ” in the .box. That’s how simple it is.

@mixin BoxCenter() {
  display: flex;
  justify-content: center;
  align-items: center;
}

.box {
  width: 100px;
  height: 100px;
  color: red;
  @include BoxCenter();
}

Output

Let’s look at the css output. While reading this article, I assume that you know how to compile scss and get css output.

.box {
  width: 100px;
  height: 100px;
  color: red;
  display: flex;
  justify-content: center;
  align-items: center;
}

Creating and using a parameterized mixin

In general, it is more preferred to create mixins with parameters.

@mixin BoxCenter($d, $jc, $ai) {
  display: $d;
  justify-content: $jc;
  align-items: $ai;
}

.box {
  width: 100px;
  height: 100px;
  color: red;
  @include BoxCenter(flex, start, end);
}

Output

The output of the above code will be as follows.

.box {
  width: 100px;
  height: 100px;
  color: red;
  display: flex;
  justify-content: start;
  align-items: end;
}

Yes, in this blog post you have learned how to create and use mixins with or without parameters in scss. I agree that you will definitely create your own mixins while using scss. ? Goodbye to see you in my next blog post.

Leave a Reply

Your email address will not be published. Required fields are marked *