SASS Mixins Tutorial

SASS Mixins Tutorial

Learn How to Use SASS Mixins

ยท

1 min read

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);
}

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;
  }
}

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;
}

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

@include transform (rotate(20deg));

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!

๐ŸŒŽ Let's Connect

ย