Sass @mixin And include

Sass @ mixin provides the facility to reuse the CSS code. This functionality reduces the amount of code. You can write it once and reference it as per requirement.

Basic Step To create Mixin

Sass mixin can be created very easily by using the @mixin followed by its name i.e @mixin HeadingColor .

Sass @mixin Syntax:

    
@mixin name{
  property: value;
  property: value;
  ...
}
   

SCSS Syntax:

    
 @mixin headingText {
  color: black;
  font-size: 25px;
  font-weight: bold;
}
   

How To Reference @mixin

It can be referenced with @include followed by the name of the mixin.

So, to include the headingText mixin created above:

SCSS Syntax:

    
 .headingElement {
  @include headingText;
  
}
   

SASS Syntax:

General Syntax

      
    
Try it now

Source Code

          <style>
.headingElement {
	color: black;
	font-size: 25px;
	font-weight: bold;
}
</style>
        
Try it now

Mixin's Argument

A mixin can also accept the argument. Let us understand it.

SCSS Syntax:

    
   /* Define mixin with two arguments */
 @mixin Elementbordered($color, $width,$borderStyle) {
  border: $width $borderStyle $color;
}

.main-container{
  @include bordered(blue, 1px,solid); 
}

.centeredContainer {
  @include bordered(red, 2px,dotted); 
}
   

After transpilation, the CSS code will be:

CSS Output:

General Syntax

      
    
Try it now

Source Code

          <style>
.main-container {
  border: 1px solid blue;
}

.centeredContainer {
  border: 2px dotted red;
}
</style>
        
Try it now

Mixin Default Value

Let us define a default value for mixin.

Mixin Statement

    
//mixing statement
@mixin Outerbordered($color: blue, $width: 1px,$style:solid) {
  border: $width $style $color;
}
   

Including Mixing

    
.container{
  @includeOuterbordered($color:grey); 
}
   

After transpiling the above sass code, the output CSS will be:

General Syntax

      
    
Try it now

Source Code

          <style type="text/css">

.container {
  border: 1px solid grey;
}

</style>
        
Try it now

Mixin For Vendor Prefixes

Let us see the mixin vendor prefix features.

    
//scss syntax
@mixin borderRadius($value) {
  -webkit-border-radius: $value;
  -ms-border-radius: $value;
  border-radius: $value;
}
   

Let us include the above mixing code.

    
.customBox {
  @include borderRadius(10px);
   background-color:lightgrey;
  padding:10px; 
}
   

After transpiring the above sass code, the resultant CSS code will be.

General Syntax

      
    
Try it now

Source Code

          <style type="text/css">
.customBox {
  -webkit-border-radius: 10px;
  -ms-border-radius: 10px;
  border-radius: 10px;
  background-color:lightgrey;
  padding:10px; 
}
</style>
        
Try it now

Web Tutorials

SASS @mixin And @include
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4