How to concatenate Sass variables

Viewed 44283

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

4 Answers

Use this:

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

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.

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.

Related