Default values let you set a variable only if it hasn't been set before. This helps avoid overwriting important settings.
0
0
Default values with !default in SASS
Introduction
When you want to provide a fallback color for a theme but allow users to change it.
When creating reusable components that need default spacing but can be customized.
When sharing variables across multiple files and want to avoid conflicts.
When building a library or framework that others will customize.
When you want to keep your styles flexible and easy to update.
Syntax
SASS
$variable: value !default;The !default flag sets the variable only if it is not already set.
If the variable has a value, the !default assignment is ignored.
Examples
This sets
$primary-color to blue only if it is not set yet.SASS
$primary-color: blue !default;The first sets
$font-size to 16px. The second is ignored because $font-size is already set.SASS
$font-size: 16px !default; $font-size: 18px !default;
Since
$margin is already 1rem, the !default assignment to 2rem does nothing.SASS
$margin: 1rem; $margin: 2rem !default;
Sample Program
This example shows how !default keeps the user's $primary-color and does not overwrite it with the default blue. The background uses the user's color, and the text color is a darker shade.
SASS
@use 'sass:color'; // User sets a color before importing defaults $primary-color: #ff6347; // Default color set with !default $primary-color: #3498db !default; body { background-color: $primary-color; color: color.scale($primary-color, $lightness: -40%); }
OutputSuccess
Important Notes
Use !default to make your Sass variables flexible and easy to override.
Place default variables in a separate file to keep your code organized.
Remember, !default only works if the variable is not set yet.
Summary
Default values let you set variables only if they are not already set.
Use !default to avoid overwriting user or previously set values.
This helps make your styles flexible and customizable.