'How to concatenate Sass variables
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
Solution 1:[1]
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
Solution 2:[2]
Use this:
$domain: 'domain.ru';
#some-div {
background-image: url('#{$domain}/images/img.jpg');
}
Solution 3:[3]
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.
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mr. Alien |
Solution 2 | |
Solution 3 | Marius |
Solution 4 | Eduardo Leffa Abrantes |