SCSS Mixins

โœ๏ธ

Deep dive into @mixins, a very powerfull SCSS addition

2 Aug, 2020 ยท 2 min read

Let's get a closer look at using @mixins in SCSS. You can look at mixins like the import we used before. But mixins place a certain set of codes on the element we are mixing in.

Defining our Mixin

We use the @mixin directive to define our mixin, so let's go ahead and create our first one:

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

Note: Naming in SCSS can be either with - or _ they are considered the same and can be used at the same time!

Using our Mixin

To use our mixin we simply use the @include statement:

.container {
  @include flex-center;
  height: 100vh;
}

Our properties on the mixin will now also exist on the container element.

Mixin inside a Mixin

Another cool thing we can do is use mixins inside each other like so:

@mixin font {
  font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
  font-size: 2rem;
}
@mixin flex {
  display: flex;
}
@mixin flex-center {
  @include flex;
  @include font;
  justify-content: center;
  align-items: center;
}

Mixin and Arguments

Something that is really strong for using mixins is the use of arguments.

We can define our mixin as such:

@mixin button($background: blue, $padding: 10px, $color: #fff) {
  background: $background;
  padding: $padding;
  display: block;
  border-radius: 5px;
  color: $color;
}

Note: We added default parameters, but these are not mandatory, you can leave them out.

And once we call it, pass these arguments:

.box {
  @include button(#7afdd6, 20px, #ffffff);
}

Pro-tip

A really good pro-tip is to use Mixins for vendor prefixes! It will safe you so much time for border-radius for example:

@mixin border-radius($amount) {
  /* Safari 3-4, iOS 1-3.2, Android 1.6- */
  -webkit-border-radius: $amount;
  /* Firefox 1-3.6 */
  -moz-border-radius: $amount;
  /* Opera 10.5, IE 9, Safari 5, Chrome, Firefox 4, iOS 4, Android 2.1+ */
  border-radius: $amount;
}

And we use this like so:

@include border-radius(20px);

Have a play around with these examples on Codepen.

See the Pen SCSS Mixins by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

Bringing perspective to CSS

7 Aug, 2022 ยท 2 min read

Bringing perspective to CSS

Creating a 3D Cylinder shape in CSS

29 Jul, 2022 ยท 3 min read

Creating a 3D Cylinder shape in CSS