Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have a variable in images path in Sass?

Tags:

css

sass

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.

like image 597
program247365 Avatar asked Dec 22 '11 18:12

program247365


People also ask

Where do you declare variables in Sass?

Sass variables are only available at the level of nesting where they are defined. Will the color of the text inside a <p> tag be red or green? It will be red! The other definition, $myColor: green; is inside the <h1> rule, and will only be available there!

How do I assign a Sass variable to a variable in CSS?

To convert the SASS variable to a CSS custom property you put curly brackets around it, and a hash in front. If you've used template literals in JavaScript it's the same thing, just with a # instead of a $ (because we already have $ in the variable name).


2 Answers

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0; 
like image 93
Wesley Murch Avatar answered Oct 17 '22 23:10

Wesley Murch


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.

like image 31
steveax Avatar answered Oct 18 '22 01:10

steveax