SASS: Why you should use mixins instead of extends

While working on some bigger projects and not only on my own small-scale websites, I noticed the current trend of using the “@extend”-syntax in order to keep your code clean. This short article will explain why you should almost never use extends.

Let’s take a quick look at one code example:

As you can see, the code is pretty straight forward. Styling elements the way I did in this example, is definitely not recommended though. I personally prefer using the BEM-syntax, but that’s another topic.

There isn’t much to say about the example itself. As you can see I used extends here, to get my basic headline styling to all necessary elements. Now comes the fun part: What gets compiled from this?

As you can see, we’re right now in selector-hell. It’s warm down there, but you’ll never get out again. It may look organised now, but imagine that code minified in your chrome dev tools. In a bigger project. No fun. Not at all.

Now the question is: what can we do to keep our code clean, readable, but still as variable as before? Mixins to the rescue!

You don’t need to change much — in the end you have just six characters more in your code than before (per mixin). Here is the example of the changed code:

As mentioned before, the extends got replaced by mixins. Not much work to do. The awesomeness starts when we take a look at the compiled results:

Pretty, huh?

You may also have noticed the short comments on top of the compiled results. Those aren’t just there because the awesome compiler of added them itself, no, I crunched some Numbers:

The extend-version of the code takes the compiler 0.065 seconds to compile. This doesn’t sound much, indeed. But let’s compare this to the time from the mixin-version: stunning 0.002 seconds. You can test it yourself. We just saved 97% of your compile time, with adding six chars to the code (or changing 34 altogether).

Let’s do a short recap: Using mixins instead of extends saves you a lot of compile time and eases your debugging. Two perfect reasons to ban extends from your code in this case.