0
0
SASSmarkup~5 mins

State class generation (hover, active, disabled) in SASS

Choose your learning style9 modes available
Introduction

State classes help change how buttons or links look when you hover, click, or disable them. This makes websites easier to use and understand.

You want a button to change color when someone moves their mouse over it.
You want a link to look pressed when clicked.
You want to show a button as disabled so users know it can't be clicked.
You want consistent styles for interactive elements across your site.
You want to write less code by generating these states automatically.
Syntax
SASS
@mixin state-classes($base-class) {
  .#{$base-class} {
    &:hover {
      // hover styles here
    }
    &:active {
      // active styles here
    }
    &.disabled, &[disabled] {
      // disabled styles here
      pointer-events: none;
      opacity: 0.5;
    }
  }
}

The @mixin helps create reusable style blocks.

Use & to refer to the current selector inside nested rules.

Examples
This mixin creates hover, active, and disabled states for a class you provide.
SASS
@mixin state-classes($base-class) {
  .#{$base-class} {
    &:hover {
      background-color: lightblue;
    }
    &:active {
      background-color: blue;
      color: white;
    }
    &.disabled, &[disabled] {
      opacity: 0.5;
      pointer-events: none;
    }
  }
}
This applies the state styles to elements with the class btn.
SASS
@include state-classes('btn');
Basic button styles before states are added.
SASS
.btn {
  background-color: gray;
  color: black;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  cursor: pointer;
}
Sample Program

This code creates a mixin to add hover, active, and disabled states to a button class. Then it includes the mixin for the btn class and sets basic button styles. The button changes color on hover and active, and looks faded and unclickable when disabled.

SASS
@mixin state-classes($base-class) {
  .#{$base-class} {
    &:hover {
      background-color: lightblue;
    }
    &:active {
      background-color: blue;
      color: white;
    }
    &.disabled, &[disabled] {
      opacity: 0.5;
      pointer-events: none;
      cursor: not-allowed;
    }
  }
}

@include state-classes('btn');

.btn {
  background-color: gray;
  color: black;
  padding: 0.5rem 1rem;
  border-radius: 0.25rem;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.3s ease, color 0.3s ease, opacity 0.3s ease;
}
OutputSuccess
Important Notes

Use pointer-events: none; on disabled states to prevent clicks.

Adding cursor: not-allowed; helps users see the button is disabled.

Transitions make state changes smooth and nicer to see.

Summary

State classes help show different looks for hover, active, and disabled states.

Use a Sass mixin to create these states easily for any class.

Disabled states should prevent clicks and show a faded look.