Understanding Interpolation in SASS

Understanding Interpolation in SASS

How to Use Interpolation to Make SASS Code More Dynamic

Interpolation is essentially a code insertion. It allows us to interpolate SASS expressions into our code. We can use it to use a selector or property name, quoted or unquoted strings, etc, as variables.

The Syntax

To interpolate an expression we need to wrap the expression using #{ }.

#{$variable_name}

Let’s see an example that shows how we could use interpolation with a mixin:

@mixin interpolation($editable, $val, $val2, $prop1, $prop2)
{
    background-#{$editable}: $val;
    position: $val2;
    #{$prop1}: 0px; 
    #{$prop2}: 0px;
}


.block1{
    @include interpolation("image", url("img.png"), absolute, top, right);
}

.block2{
    @include interpolation("color", lightgray, absolute, top, left);
}

This will compile in CSS as follows:

.block1 {
    background-image: url("img.png");
    position: absolute;
    top: 0px;
    right: 0px;
}

.block2 {
   background-color: lightgray;
   position: absolute;
   top: 0px;
   left: 0px;
}

As you can see, it’s quite easy to use this to create dynamically reusable code!

Main Reasons to Use Interpolation

  • We can use dynamically created names as a property name, a variable name, or for other similar purposes.
  • We can create highly reusable code!

In the next article, we’ll learn how to use placeholders in SASS.

Conclusion

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

🌎 Let's Connect

Did you find this article valuable?

Support Richard Rembert by becoming a sponsor. Any amount is appreciated!