Have a variable in images path in Sass?

CssSass

Css Problem Overview


I want to have one variable that contains the root path to all my images in my CSS file. I can't quite figure out if this is possible in pure Sass (the actual web project is not RoR, so can't use asset_pipeline or any of that fancy jazz).

Here's my example that doesn't work. On compile it balks at first instance of variable in the background url property saying ("Invalid CSS after "..site/background": expected ")").

Defining the function to return the path:

//Vars
$assetPath : "/assets/images";

//Functions
@function get-path-to-assets($assetPath){
  @return $assetPath;
}

Using the function:

body {
  margin: 0 auto;
  background: url($get-path-to-assets/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

Any help would be appreciated.

Css Solutions


Solution 1 - Css

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

Solution 2 - Css

No need for a function:

$assetPath : "/assets/images";

...

body {
  margin: 0 auto;
  background: url(#{$assetPath}/site/background.jpg) repeat-x fixed 0 0;
  width: 100%; }

See the interpolation docs for details.

Solution 3 - Css

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

Solution 4 - Css

Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg) this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!

url("#{$assetPath}/site/background.jpg")

Solution 5 - Css

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionprogram247365View Question on Stackoverflow
Solution 1 - CssWesley MurchView Answer on Stackoverflow
Solution 2 - CsssteveaxView Answer on Stackoverflow
Solution 3 - CssNerdCowboyView Answer on Stackoverflow
Solution 4 - CssPons PurushothamanView Answer on Stackoverflow
Solution 5 - CssAarji GeorgeView Answer on Stackoverflow