/blog/articles/

Use a Sass variable inside a string with Interpolation

One of my favourite features of Sass are variables. Let's say you define a variable like that:

$wrap-width: 1200px;

And then you want to use that variable inside a string of another one, for example a media query variable. Then this

won't work:

$mq--wrap: '(max-width: $wrap-width)';

Instead you need to use the #{} interpolation syntax of Sass, like that:

$mq--wrap: '(max-width: #{$wrap-width})';

This way Sass recognises $wrap-with as a variable and replaces it with 1200px. You also need to interpolate a variable if you want to do something like this:

$gap: 20px;

.my-class {
    margin-top: -#{$gap};
}

This will generate to following output:

.my-class {
    margin-top: -20px;
}

UPDATE:

It turns out the last example is wrong.

Click here for proof. At least in Sass v3.4.0. I could swear I had trouble with that somewhen in the past. Thanks @FWeinb.

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.