0
0
SASSmarkup~5 mins

Why variables reduce repetition in SASS

Choose your learning style9 modes available
Introduction

Variables help you write code once and use it many times. This saves time and makes your code easier to change.

When you use the same color in many places on your website.
When you want to keep font sizes consistent across different sections.
When you need to update a spacing value used in multiple places.
When you want to quickly change a theme color without searching all your code.
When you want to avoid mistakes by typing the same value repeatedly.
Syntax
SASS
$variable-name: value;
Variables start with a dollar sign ($) in Sass.
You assign a value once and reuse the variable name later.
Examples
Defines a variable named $main-color with a blue color value.
SASS
$main-color: #3498db;
Uses the $main-color variable to set the background color.
SASS
body {
  background-color: $main-color;
}
Stores padding size in a variable and applies it to a container.
SASS
$padding: 1.5rem;
.container {
  padding: $padding;
}
Sample Program

This Sass code defines variables for colors and padding. It uses these variables to style the body and buttons. If you want to change the main colors or padding, you only need to update the variables.

SASS
@use 'sass:color';

$primary-color: #ff6347;
$secondary-color: #4caf50;
$base-padding: 1rem;

body {
  background-color: $primary-color;
  color: white;
  padding: $base-padding;
}

button {
  background-color: $secondary-color;
  padding: $base-padding;
  border: none;
  color: white;
  font-weight: bold;
}

button:hover {
  background-color: color.scale($secondary-color, $lightness: -20%);
}
OutputSuccess
Important Notes

Changing a variable value updates all places where it is used automatically.

Variables make your code cleaner and easier to read.

Use meaningful variable names to remember what each value means.

Summary

Variables store values you use many times.

They reduce repetition and make updates easy.

Sass variables start with $ and can hold colors, sizes, or any value.