Open In App

SASS variable for images path

Last Updated : 27 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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%; 
}

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads