Setting Default Values with Variables

Tutorial 3 of 5

Introduction

Welcome to this tutorial on setting default values for your SASS/SCSS variables using the '!default' flag. The goal of this tutorial is to help you understand how to define default values for SASS/SCSS variables, which can be overridden with actual values later.

By the end of this tutorial, you will learn:

  • What SASS/SCSS is.
  • What SASS/SCSS variables are.
  • How to set default values for SASS/SCSS variables using the '!default' flag.

Prerequisites: Basic knowledge of CSS and a general understanding of SASS/SCSS.

Step-by-Step Guide

SASS/SCSS Variables

In SASS/SCSS, variables allow you to store reusable values like colors, font-sizes, or complex values and use them in various parts of your code. You define a variable in SASS/SCSS with a $ symbol.

Default Values in SASS/SCSS

The !default flag is a way to specify a default value for a SASS/SCSS variable that can later be overridden.

Best Practices and Tips

  • It's a good practice to use the !default flag for those values which you think might change in the future.
  • Use meaningful variable names to make the code more readable and maintainable.

Code Examples

Basic Example

$font-color: null !default;
$font-color: blue;

body {
  color: $font-color; // This will output blue
}

In the above code snippet:

  • We have declared a variable $font-color with a null value and a !default flag.
  • Then we have defined $font-color again with the value blue.
  • In the body selector, we use the $font-color variable. Since we have already defined the $font-color after the !default declaration, it will output blue.

Expected CSS output:

body {
  color: blue;
}

Advanced Example

$font-color: red !default;

@import 'custom';

body {
  color: $font-color; // This will output blue if $font-color is defined in _custom.scss
}

In this example, if $font-color is defined in _custom.scss, it will override the default value. If not, the default value red will be used.

Summary

In this tutorial, you have learned how to set default values for your SASS/SCSS variables using the '!default' flag. The '!default' flag is a powerful tool that allows you to define default values for your variables that can be overridden if required.

For further learning, you can explore how to use SASS/SCSS with CSS frameworks like Bootstrap or Foundation.

Practice Exercises

Exercise 1: Create a SCSS file and define some variables with default values using the !default flag.

Exercise 2: Now override those variables with new values in the same SCSS file and compile it to CSS. Observe the output.

Exercise 3: Create a second SCSS file. Import it into your first file and try to override the default variables from the second file.

Tips for Further Practice: Play around with different types of values (not just colors) and observe how the !default flag works in different situations.