SASS variable for images path

Whenever we want to add an image to our webpage, we need not always write the full path of our images when using SASS. We can rather store the path to the images folder in a variable. It is always good to add the path of a folder to a variable.

Declaring a variable
Syntax :

$assetPath :"path";

Adding a variable in image path
Syntax :

background: url(#{$assetPath}/gfg.gif);

Example 1: SASS file

$assetPath :"/assets/images";
body {
  margin: 0 auto;
  background: url(#{$assetPath}/gfg.gif);
  width: 100%; 
}

Output: Compiled CSS file



body {
  margin: 0 auto;
  background: url(/assets/images/gfg.gif);
  width: 100%; 
}

We can also use multiple variables in a single path to an image.

Syntax :

background: url(#{$variable1}/#{$variable2}/#{$variable3});

Example 2: SASS file

$assetsPath :"/assets/images";
$project :"project2";
body {
  margin: 0 auto;
  background: url(#{$assetsPath}/#{$project}/gfg.gif);
  width: 100%; 
}

Output: Compiled CSS file

body {
  margin: 0 auto;
  background: url(/assets/images/project/gfg.gif);
  width: 100%; 
}
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.