Building Reusable Components with SASS
SASS enhances CSS by introducing programming capabilities, improving development efficiency, and extending styling techniques.
Component-Based Design
Consider designing a form notification component that supports multiple states (success, warning, error). CSS requires defining base styles for typography, spacing, display properties, borders, and other attributes, followed by state-specific variations.
Traditional CSS Approach
Base styles are defined first, then each state receives its own style set:
.alert {
padding: 15px;
margin-bottom: 20px;
border-radius: 4px;
}
.alert-success {
background-color: #47a447;
color: #fff;
}
.alert-warning {
background-color: #ed9c28;
color: #fff;
}
.alert-error {
background-color: #d2322d;
color: #fff;
}
Each state requires individual color and border definitions, creating maintainance overhead when adding new states like info or danger.
SASS Component Implementation
SASS provides programming constructs that encapsulate data and methods for reusable components.
Default Variables with !default
The !default flag indicates that a variable's value can be overridden by global declarations:
$primary-color: blue;
$primary-color: red !default;
p {
color: $primary-color; // Outputs: blue
}
Using Mixins
Mixins define reusable style blocks:
@mixin alert-style($bg, $text, $padding) {
background-color: $bg;
color: $text;
padding: $padding;
margin-bottom: 20px;
border-radius: 4px;
}
Mixins are invoked using @include:
.alert-success {
@include alert-style(#47a447, #fff, 15px);
}
.alert-warning {
@include alert-style(#ed9c28, #fff, 15px);
}
.alert-error {
@include alert-style(#d2322d, #fff, 15px);
}
Component File Structure
Create a modular SASS component file (_alerts.scss):
// Variables
$alert-bg: #47a447 !default;
$alert-text: #fff !default;
$alert-padding: 15px !default;
// Mixin
@mixin alert-style($bg, $text, $padding) {
background-color: $bg;
color: $text;
padding: $padding;
margin-bottom: 20px;
border-radius: 4px;
}
// Styles
.alert-success {
@include alert-style($alert-bg, $alert-text, $alert-padding);
}
.alert-warning {
@include alert-style(#ed9c28, $alert-text, $alert-padding);
}
.alert-error {
@include alert-style(#d2322d, $alert-text, $alert-padding);
}
Import the component where needed:
@import 'alerts';
Customizing Components
Override default variables before import:
$alert-padding: 5px;
@import 'alerts';
This produces clean output without duplicate declarations:
.alert-success {
background-color: #47a447;
color: #fff;
padding: 5px;
margin-bottom: 20px;
border-radius: 4px;
}
Variable Design Principles
- All variables should have default values with !default for easy overriding
- Use boolean variables (true/false) as feature flags for conditional styling
- Consider compound variables to reduce variable count when appropriate