How to use variables in Sass?

In Sass (Syntactically Awesome Style Sheets), you can use variables to store and reuse values throughout your stylesheets. This allows you to define a value once and use it in multiple places, making your code more efficient and easier to maintain. Here’s how you can use variables in Sass:

  1. Variable Declaration: To declare a variable in Sass, you use the $ symbol followed by the variable name and the value you want to assign to it. For example:
$primary-color: #FF0000;

In this example, the variable $primary-color is assigned the value #FF0000, which represents a red color.

  1. Variable Usage: Once you’ve declared a variable, you can use it by referencing its name wherever you need to use the corresponding value. For instance:
h1 {
  color: $primary-color;
}

In this case, the h1 elements will have the color value of the $primary-color variable, which is #FF0000 (red).

  1. Variable Scope: Variables in Sass have scope, which means they are only accessible within the block of code where they are defined. If you declare a variable within a nested block, it will be accessible only within that block and its child blocks. Here’s an example:
$primary-color: #FF0000;

body {
  $background-color: #F0F0F0;
  background-color: $background-color;

  h1 {
    color: $primary-color;
  }
}

In this case, the $primary-color variable is accessible within the h1 element, while the $background-color variable is only accessible within the body element.

  1. Variable Overriding: You can also override the value of a variable by reassigning it later in your code. The new value will then be used throughout the rest of the stylesheet. For example:
$primary-color: #FF0000;

h1 {
  color: $primary-color;
}

// Later in the code...
$primary-color: #00FF00;

h2 {
  color: $primary-color;
}

In this case, the h1 elements will have the initial $primary-color value of #FF0000 (red), while the h2 elements will use the overridden value of #00FF00 (green).

Using variables in Sass helps streamline your stylesheets, promotes consistency, and makes it easier to update styles across your project. By defining values once and reusing them, you can save time and effort in maintaining your styles.

error: Content is protected !!