Conditional mixins let you change styles based on conditions. This helps you write flexible and reusable CSS.
0
0
Conditional mixins with @if in SASS
Introduction
You want to apply different colors based on a theme choice.
You need to add extra padding only if a certain flag is true.
You want to change font size depending on a size parameter.
You want to include or skip some styles based on a condition.
You want to keep your CSS clean by avoiding repeated code.
Syntax
SASS
@mixin mixin-name($param) { @if $param == value { // styles here } @else if $param == other-value { // other styles } @else { // default styles } }
Use @if inside a mixin to check conditions.
You can use @else if and @else for multiple cases.
Examples
This mixin sets background and text colors based on the theme.
SASS
@mixin theme-color($theme) { @if $theme == light { background-color: white; color: black; } @else if $theme == dark { background-color: black; color: white; } @else { background-color: gray; color: black; } }
This mixin changes padding size depending on the input.
SASS
@mixin padding-size($size) { @if $size == small { padding: 0.5rem; } @else if $size == large { padding: 2rem; } @else { padding: 1rem; } }
Sample Program
This example creates a button style mixin that changes styles based on the button type. Then it applies the mixin to three button classes with different types.
SASS
@use "sass:color"; @mixin button-style($type) { @if $type == primary { background-color: blue; color: white; border: none; } @else if $type == secondary { background-color: white; color: blue; border: 2px solid blue; } @else { background-color: gray; color: black; border: none; } padding: 0.75rem 1.5rem; border-radius: 0.5rem; font-weight: bold; cursor: pointer; } .button-primary { @include button-style(primary); } .button-secondary { @include button-style(secondary); } .button-default { @include button-style(default); }
OutputSuccess
Important Notes
Always test your conditions to make sure styles apply as expected.
Use meaningful parameter names to keep your mixins clear.
Conditional mixins help reduce repeated CSS and keep your code DRY (Don't Repeat Yourself).
Summary
Conditional mixins let you write flexible styles based on input values.
Use @if, @else if, and @else inside mixins for different cases.
This technique helps keep your CSS clean and reusable.