DEV Community

Cover image for Understanding Interpolation in SASS
Richard Rembert
Richard Rembert

Posted on • Edited on

Understanding Interpolation in SASS

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} 
Enter fullscreen mode Exit fullscreen mode

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); } 
Enter fullscreen mode Exit fullscreen mode

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; } 
Enter fullscreen mode Exit fullscreen mode

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!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

Top comments (0)