DEV Community 👩‍💻👨‍💻

Ed is Taking Note
Ed is Taking Note

Posted on

Difference between Mixin and Placeholder in SASS

In SASS, Mixin and Placeholder are really similar. They can hold combination of css properties and can be reused in many places, just like variables to help reduce our codes. However, they actually work differently behind the scene.

  • Mixin - It copies the mixin to the place where it is used.

  • Placeholder - It copies the selectors that use the placeholder to the place where the placeholder declared.

Let's see the following example:
We declared a mixin bananaColor, and a placeholder coffeeBackground.

They are used by the following classes:
.paragraph1 uses bananaColor.
.paragraph2 uses bananaColor and coffeeBackground.
.paragraph3 uses coffeeBackground.

SASS file:

@mixin bananaColor {
  color: #f5c725;
  font-weight: 600;
}

%coffeeBackground {
  background-color: #b46427;
  padding: 10px;
}

.paragraph1 {
  font-size: 20px;
  height: 100px;

  @include bananaColor;
}

.paragraph2 {
  font-size: 20px;
  height: 100px;

  @include bananaColor;
  @extend %coffeeBackground
}

.paragraph3 {
  font-size: 20px;
  height: 100px;

  @extend %coffeeBackground
}
Enter fullscreen mode Exit fullscreen mode

Html File:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <div>
            <p class="paragraph1">paragraph 1</p>
            <p class="paragraph2">paragraph 2</p>
            <p class="paragraph3">paragraph 3</p>
        </div>
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

The result is like:
Image description

Let's compare how SASS compiles the code.

For Mixin, it copies the declared mixin properties to places where it is used.
Image description

For placeholders, it copies the selectors(.paragraph2, .paragraph3) to the placeholder where it is declared.
Image description

In conclusion, we can see Mixin and Placeholder are literally doing things reversely.

The logic of Mixin could be more intuitive and understandable than Placeholer. However, it may result in larger CSS code because it just copies the declared Mixin to everywhere, while Placeholder only copies the selectors.

Apart from that, Mixin can work like a function. We can also pass parameters into a Mixin, while we cannot use parameters on Placeholder.

Mixin and Placeholder can really help us organize and reduce our SASS code. We can choose to use either Mixin or Placeholder depending on our actual scenarios.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. 🌈