SCSS: Placeholders vs Mixins

Linker
3 min readJan 7, 2019
Credit: Code Like a Girl

Using a CSS preprocessor can make writing code faster and easier, giving you the flexibility to accomplish more in CSS and have time to get to other, equally important tasks. It’s common for these preprocessors to provide a means of grouping properties for those specified properties to be used repeatedly throughout a program.

SCSS is one such preprocessor, the younger, cooler (more standard) sibling to Sass. It has not just one, but two ways to group code and use it over and over again. Upon first glance, it can be difficult to determine what the real differences are between them, but rest assured, there are clear places where one is superior to the other.

Overview

Mixins are common to both LESS and SCSS, the two most popular CSS preprocessors, with slight differences between them. They can take arguments and use them within the mixin.

// MIXIN SYNTAX @mixin mixin-name {
// your code here
}
// To call your mixin
selector {
@include mixin-name;
}

Placeholders serve the same basic purpose as mixins, but without arguments and with different syntax.

// PLACEHOLDER SYNTAX %placeholder-name {
// your code here
}
// To call your placeholder
selector {
@extend %placeholder-name;
}

Which one is superior?

Depends. If you need to pass variables, it’s better to use mixins. If not, use placeholders. To illustrate why, let’s look at a simple experiment.

Let’s define one placeholder and one mixin. They’ll have the same code, a short series of properties that will help us identify them.

@mixin mixin-test {
background-color: blue;
width: 300px;
height: 400px;
}
%extend-test {
background-color: yellow;
width: 300px;
height: 400px;
}

These will be distributed among four classes, each corresponding to empty div elements.

The assignments will show the differences between how mixins and placeholders compile to CSS. The version that optimizes readability and efficiency is the one we should default to. The compiled CSS ends up looking like this:

The difference between mixins and placeholders is that placeholders consolidates mutually-shared code, whereas mixins just assign the properties to the individual classes — along with whatever was specific to that class. Because of this, it’s preferential to use placeholders when possible, and it’s not always possible. As mentioned earlier, placeholders aren’t able to take parameters, making them less useful when code is dependent upon variables. It’s better to use mixins in those cases.

--

--