Sass Variables

Sass Tutorial

Sass Variables

Sass Variables are used to store values like colors, fonts, sizes, spacing, and reusable data that you can use again and again in your stylesheet.
They make your CSS cleaner, consistent, and easier to maintain.


 Variable Syntax in Sass

In Sass, variables start with the $ symbol.

$primary-color: #3498db;
$font-size: 16px;
$font-family: Arial, sans-serif;

 Using Variables

$main-color: #ff5722;

body {
background-color: $main-color;
}

button {
background-color: $main-color;
}

✔ If you change $main-color, it updates everywhere.


 Types of Sass Variables

1️⃣ Color Variables

$primary: #0d6efd;
$secondary: #6c757d;
h1 {
color: $primary;
}

2️⃣ Number Variables

$padding: 20px;
$width: 100%;
.box {
padding: $padding;
width: $width;
}

3️⃣ String Variables

$font: "Roboto";

body {
font-family: $font;
}


4️⃣ Boolean Variables

$rounded: true;

(Used mainly with conditions & mixins)


5️⃣ List Variables

$margin-list: 10px 20px 30px;

.box {
margin: $margin-list;
}


6️⃣ Map Variables (Key–Value Pair)

$colors: (
primary: #ff0000,
success: #28a745,
danger: #dc3545
);
.button {
background-color: map-get($colors, primary);
}

 Variable Scope

Global Variable

$color: blue;

p {
color: $color;
}


Local Variable

.box {
$color: red;
background-color: $color;
}

⚠️ Local variables work only inside that block.


 Default Variables (!default)

Used when you want to override variables later.

$theme-color: green !default;

button {
background-color: $theme-color;
}


 Variable Interpolation

Use variables inside strings or selectors.

$size: large;

.btn-#{$size} {
padding: 20px;
}

Output:

.btn-large {
padding: 20px;
}

 Real-Life Example

$primary: #2196f3;
$radius: 5px;
.card {
border: 1px solid $primary;
border-radius: $radius;
}

Benefits of Sass Variables

✔ Easy theme changes
✔ Consistent design
✔ Less repetition
✔ Faster development


📌 Summary

  • Variables start with $

  • Can store colors, numbers, strings, lists, maps

  • Support scope & default values

  • Improve code readability & maintenance

You may also like...