Categories
Web development

Sass @mixin and @include

Sass lets you use features that don’t exist in CSS yet like variables, nesting, mixins, inheritance, and others. The @mixin directive lets you create CSS code that is to be reused throughout the website. The @include directive is created to let you use (include) the mixin.

Web developer
Do you like this gif? Check more gifs in the store.

Mixins allow you to define styles that can be re-used throughout your stylesheet. They make it easy to avoid using non-semantic classes like .float-left and to distribute collections of styles in libraries.

A mixin is defined with the @mixin directive:

Sass @mixin Syntax:

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

The following example creates a mixin named “important-text”:

SCSS Syntax:

@mixin important-text {
  color: blue;
  font-size: 25px;
  font-weight: bold;
  border: 2px solid green;
}

The @include directive is used to include a mixin:

Sass @include mixin Syntax:

selector {
  @include mixin-name;
}

SCSS Syntax:

.read {
  @include important-text;
  background-color: pink;
}

Output:

Sass @mixin and @include

A mixin can also include other mixins:

@mixin special-text {
  @include important-text;
  @include link;
  @include special-border;
}

Passing Variables to a Mixin

Mixins accept arguments. This way you can pass variables to a mixin.

Here is how to define a mixin with arguments:

@mixin bordered($color, $width) {
  border: $width solid $color;
}

.myArticle {
  @include bordered(green, 2px);
}

.myNotes {
  @include bordered(blue, 2px);

Notice that the arguments are set as variables and then used as the values (color and width) of the border property.

Sass @mixin and @include

Default Values for a Mixin

It is also possible to define default values for mixin variables:

SCSS Syntax:

@mixin bordered($color: blue, $width: 1px) {
  border: $width solid $color;
}

Then, you only need to specify the values that change when you include the mixin:

SCSS Syntax:

.myTips {
  @include bordered($color: orange);
}

Using a Mixin For Vendor Prefixes

Another good use of a mixin is for vendor prefixes.

SCSS Syntax:

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}

.myBox {
  @include transform(rotate(20deg));
}

After compilation, the CSS will look like this:

.myBox {
  -webkit-transform: rotate(20deg);
  -ms-transform: rotate(20deg);
  transform: rotate(20deg);
}

Enjoy coding!

Read also:

CSS Glowing Gradient Border

CSS Gradient Border