Component variant generation helps you create different styles of the same element easily. It saves time and keeps your code organized.
Component variant generation in SASS
@mixin component-variant($name) { &--#{$name} { @content; } } .component { // base styles @include component-variant('variant-name') { // variant styles } }
The @mixin defines reusable style blocks.
The &--#{$name} creates a modifier class like .component--variant-name.
.button--red and .button--blue with different background colors.@mixin button-variant($color) { &--#{$color} { background-color: $color; color: white; } } .button { padding: 1rem 2rem; border-radius: 0.5rem; font-weight: bold; @include button-variant(red); @include button-variant(blue); }
@mixin alert-variant($bg-color, $text-color) { &--custom { background-color: $bg-color; color: $text-color; padding: 1rem; border-radius: 0.25rem; } } .alert { font-size: 1rem; font-weight: 600; @include alert-variant(green, white); }
This example shows two buttons with different colors using component variant generation in Sass. The base .button class has common styles. The variants .button--red and .button--blue add different background colors. Hover effects darken the colors for better interaction feedback.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Button Variants</title> <style type="text/scss"> $red: #e63946; $blue: #457b9d; @mixin button-variant($color) { &--#{$color} { background-color: $color; color: white; border: none; cursor: pointer; @content; } } .button { padding: 1rem 2rem; border-radius: 0.5rem; font-weight: bold; font-family: Arial, sans-serif; margin: 0.5rem; transition: background-color 0.3s ease; @include button-variant(red) { background-color: $red; } @include button-variant(blue) { background-color: $blue; } } .button--red:hover { background-color: darken($red, 10%); } .button--blue:hover { background-color: darken($blue, 10%); } </style> </head> <body> <button class="button button--red" aria-label="Red button">Red Button</button> <button class="button button--blue" aria-label="Blue button">Blue Button</button> </body> </html>
Use meaningful variant names to keep your code easy to understand.
Component variants help keep your CSS DRY (Don't Repeat Yourself).
Always test your variants on different screen sizes for good responsiveness.
Component variant generation creates different styles for the same element easily.
Use Sass mixins with dynamic class names for flexible variants.
Variants keep your styles organized and reusable.