0
0
SASSmarkup~15 mins

@else and @else if branches in SASS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @else and @else if branches in Sass
📖 Scenario: You are creating a simple Sass stylesheet for a website that changes the background color of a button based on its type. The button can be primary, secondary, or danger. If the type is not one of these, it should have a default background color.
🎯 Goal: Build a Sass code snippet that uses @if, @else if, and @else branches to set the background color of a button based on its $type variable.
📋 What You'll Learn
Create a Sass variable called $type with the value 'primary'.
Create a variable called $primary-color with the value #007bff.
Create a variable called $secondary-color with the value #6c757d.
Create a variable called $danger-color with the value #dc3545.
Use @if, @else if, and @else to set a variable $bg-color based on $type.
Write a CSS rule for .button that sets background-color to $bg-color.
💡 Why This Matters
🌍 Real World
Buttons on websites often change color based on their purpose, like primary actions or warnings. Using Sass conditionals helps manage these styles cleanly.
💼 Career
Knowing how to use @if, @else if, and @else in Sass is important for frontend developers to write maintainable and flexible stylesheets.
Progress0 / 4 steps
1
Set up the initial variables
Create a Sass variable called $type and set it to the string 'primary'. Then create three color variables: $primary-color set to #007bff, $secondary-color set to #6c757d, and $danger-color set to #dc3545.
SASS
Hint

Remember to use $variable-name: value; syntax to create variables in Sass.

2
Add a variable for background color
Create a new Sass variable called $bg-color and set it initially to null.
SASS
Hint

Use $bg-color: null; to declare the variable without a color yet.

3
Use @if, @else if, and @else to set $bg-color
Write an @if block that checks if $type is 'primary' and sets $bg-color to $primary-color. Then add an @else if branch to check if $type is 'secondary' and set $bg-color to $secondary-color. Add another @else if branch to check if $type is 'danger' and set $bg-color to $danger-color. Finally, add an @else branch that sets $bg-color to #cccccc as a default color.
SASS
Hint

Use @if and @else if with == to compare strings in Sass.

4
Create the .button rule with background color
Write a CSS rule for the class .button that sets the background-color property to the Sass variable $bg-color.
SASS
Hint

Use .button { background-color: $bg-color; } to apply the color.