Sass Variables

Sass Variables

A variable is a way to store information, which you can use repeatedly later.

Through Sass, you can:InformationGurbi a bili ko wani, dake kaiyawa:

  • String
  • Number
  • Color
  • Boolean
  • List
  • null

Sass ana gurbi $ simin bayan kowarin a bayan gurbi kowarin:

Sass kowarin jiki:

$variablename: value;

Fagenin baya ce ce bayan ce bayan ce bayan ce bayan ce kowarin 4:

  • myFont
  • myColor
  • myFontSize
  • myWidth

Bayan kowarin bayan, ana iya gurbi kowarin a kada ko wani:

SCSS Syntax:

$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 18px;
$myWidth: 680px;
body {
  font-family: $myFont;
  font-size: $myFontSize;
  color: $myColor;
}
#container {
  width: $myWidth;
}

Sannan, kada Sass fageni ke sa yancin, ana ce kowarin (myFont, myColor kuma sa rabi), kuma sa fageni CSS a bili ko wani, kuma sa gurbi kowarin dake sa yancin CSS, dake kaiyawa:

CSS Output:

body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: red;
}
#container {
  width: 680px;
}

Sass kowarin rayuwa

Sass kowarin gana yancin a bai sa bili ko wani ke sa kada ko wani kaiyawa a bili.

Kai kai kiyi fagen:

SCSS Syntax:

$myColor: red;
h1 {
  $myColor: green;
  color: $myColor;
}
p {
  color: $myColor;
}

<p> The text color within the tag is red or green? It's red!

Another definition, $myColor: green; is located <h1> within the rule, and only there available!

So, the CSS output will be:

CSS Output:

h1 {
  color: green;
}
p {
  color: red;
}

Okay, this is the default behavior of variable scope.

Using Sass !global

You can use !global Switches override the default behavior of variable scope.

!global indicating that the variable is global, which means it can be accessed at all levels.

Please see the following example (the same as above, but with !global):

SCSS Syntax:

$myColor: red;
h1 {
  $myColor: green !global;
  color: $myColor;
}
p {
  color: $myColor;
}

Now <p> The text color within the tag will be green!

So, the CSS output will be:

CSS Output:

h1 {
  color: green;
}
p {
  color: green;
}

Tip:Global variables should be defined outside any rule. It is wise to define all global variables in their own file, named "_globals.scss", and use @include Keywords include this file.