How to concatenate Sass variables
Asked Answered
A

5

43

How can I concatenate a Sass variable?

This is the the code in the scss file.

$url = 'siteurl.com';

#some-div{
    background-image: url(+ $url +/images/img.jpg);
}

I want the result in the CSS file to be:

#some-div{
    background-image: url('siteurl.com/images/img.jpg');
}

I found this question, but it didn't worked for me: Trying to concatenate Sass variable and a string

Appetitive answered 19/9, 2017 at 6:7 Comment(0)
F
62

Multiple issues here, the correct syntax is

$url: 'siteurl.com';

#some-div{
  background-image: url($url + '/images/img.jpg');
}
  • When you assign a value to the variable, you need to use : and not =
  • You should quote the image path as it's a string.
  • Remove the stray + symbol before $url

You can see the above code in action at SassMeister

Foreground answered 19/9, 2017 at 6:10 Comment(0)
B
28

Use this:

$domain: 'domain.ru';
#some-div {
    background-image: url('#{$domain}/images/img.jpg');
}
Benitabenites answered 27/5, 2019 at 14:29 Comment(3)
What is different about this answer, compared to the already accepted one?Fidelfidela
The syntax relying on string interpolation is slightly different to read and might make different sense to some people, so seems useful as an alternative. It was to me, anyway.Palsy
@stein I think this syntax is more flexible. For example, maybe you want to make a color based on an existing color like this: $accent-light: #{$accent}80; (makes a new color with 50% transparency). I believe the #{$variable} syntax can be used pretty much anywhere, whereas $variable + "some string" cannot.Bedivere
D
8

The best to do it via interpolation ( #{} ), where all strings become unquoted.

$basePath= 'example.com';

#some-div{
    background-image: url('#{$basePath}/images/photo.jpg');
}

This is a safer way for this particular use-case as you won't want any additional quotes added to your url.

During answered 10/7, 2019 at 21:37 Comment(2)
This seems to contain a syntax error in the definition for $basePathMoguel
That's because he is using equal to = instead of colon :Assentation
C
3

A example:

$dot: '0.'; 

@for $i from 1 through 9 {
  .op#{$i} {
    opacity: #{$dot}#{$i};
  }
}

By logic, the variable is declared in $dot: '0.'; and I called her in #{$dot}. This example above shows two concatenated variables in SCSS.

Celsacelsius answered 20/10, 2021 at 3:29 Comment(0)
A
1

Sep 2023

For anyone looking with quotes and without a quote

$url: 'siteurl.com';

#some-div{
    background-image: url($url + '/images/img.jpg');
}
// output with quote: "siteurl.com/images/img.jpg"

#some-div{
    background-image: url(#{$url} + '/images/img.jpg');
}
// output without quote: siteurl.com/images/img.jpg
Assentation answered 19/9, 2023 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.