0
0
SASSmarkup~5 mins

Why logic in stylesheets is needed in SASS

Choose your learning style9 modes available
Introduction

Logic in stylesheets helps make designs flexible and easier to manage. It lets you change styles based on conditions or reuse code without repeating yourself.

When you want to change colors or sizes based on a theme or user choice.
When you need to create responsive designs that adjust to screen size.
When you want to reuse style patterns with small changes.
When you want to avoid repeating the same style code multiple times.
When you want to organize your styles better for large projects.
Syntax
SASS
// Example of logic in Sass
$theme: dark;

body {
  @if $theme == dark {
    background-color: black;
    color: white;
  } @else {
    background-color: white;
    color: black;
  }
}
Sass lets you use variables to store values like colors or sizes.
You can use @if and @else to add conditions in your styles.
Examples
This example changes the container background based on the mode variable.
SASS
$mode: light;

.container {
  @if $mode == light {
    background: white;
  } @else {
    background: gray;
  }
}
Here, button padding changes depending on the size variable.
SASS
$size: large;

.button {
  @if $size == large {
    padding: 2rem;
  } @else {
    padding: 1rem;
  }
}
Using a variable to set text color makes it easy to update later.
SASS
$color: blue;

.text {
  color: $color;
}
Sample Program

This Sass code uses logic to change the background and text colors based on the theme variable. It also adjusts the button color for dark mode and adds a hover effect.

SASS
@use 'sass:color';

$theme: dark;

body {
  font-family: Arial, sans-serif;
  @if $theme == dark {
    background-color: #222;
    color: #eee;
  } @else {
    background-color: #fff;
    color: #111;
  }
}

.button {
  $base-color: #3498db;
  background-color: $base-color;
  color: white;
  padding: 1rem 2rem;
  border-radius: 0.5rem;
  border: none;
  cursor: pointer;

  @if $theme == dark {
    background-color: color.scale($base-color, $lightness: -20%);
  }

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

Logic in stylesheets helps keep your code DRY (Don't Repeat Yourself).

Using variables and conditions makes it easy to switch themes or styles globally.

Remember to compile Sass to CSS before using it in the browser.

Summary

Logic in stylesheets makes designs flexible and easier to update.

Variables and conditions help reuse code and manage themes or sizes.

Sass is a popular tool that adds logic to CSS for better style management.