DEV Community

Cover image for SASS Mixins Tutorial
Richard Rembert
Richard Rembert

Posted on • Updated on

SASS Mixins Tutorial

Mixins are an extremely powerful feature of Sass. We use them to group together multiple CSS declarations for reuse throughout our projects.

Say we want to create a mixin to hold the vendor prefixes for a transform property.

In SASS, we’d code it like so:

@mixin transform {
  -webkit-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  transform: rotate(180deg);
}
Enter fullscreen mode Exit fullscreen mode

To add the mixin into our code, we then use the @include directive, like so:

.navbar {
  background-color: red;
  padding: 1rem;
  ul {
    list-style: none;
  }
  li {
    text-align: center;
    margin: 1rem;
    @include transform;
  }
}
Enter fullscreen mode Exit fullscreen mode

All the code in the transform mixin will now be applied to the li element. You can also pass values into your mixins to make them even more flexible.

Instead of adding a specified value, add a name (using a variable, like property) to represent the value like so:

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}
Enter fullscreen mode Exit fullscreen mode

Now we can pass in whatever value we like, whenever we call the mixin:

@include transform (rotate(20deg));
Enter fullscreen mode Exit fullscreen mode

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tipβ€Šβ€”β€Šclick here

🌎 Let's Connect

Top comments (0)