Mixin Expansion vs. Class Refactoring
The primary criterion for choosing between a Stylus mixin and a native CSS class is argument variance. Because Stylus expands mixins at build time by inlining the declarations into every selector that calls them, the compiler creates a unique block of CSS for every single invocation.
When to Expand (Use Mixins)
- High Argument Variation: When the mixin is used to generate a wide array of unique values (e.g., a grid system where widths vary by 1% increments), a mixin is appropriate because the resulting CSS would be different for every element anyway.
- Logic-Driven Styles: When the output depends on complex conditional logic or loops that cannot be represented by a static class.
- Silent Mixins: Use silent mixins (defined with a
+ prefix or called with a +) for abstractions that handle logic without emitting CSS directly.
When to Refactor (Use Classes)
- Identical Output: If a mixin is called across multiple selectors with the same arguments, it creates redundant duplicate declarations in the final CSS. Refactoring this to a shared
.class reduces the output size to a single declaration block.
- High Reuse Frequency: When a set of styles is applied to dozens of different components, the cumulative size of inlined mixins can significantly inflate the bundle.
Impact of Arguments and Nesting
Argument variation directly increases duplication. Each unique combination of arguments passed to a mixin forces the compiler to generate a new set of CSS rules. If you have a mixin with three arguments and call it with five different combinations, you will have five copies of those declarations in your compiled file.
Regarding nesting, Stylus does not have a hard-coded limit on nesting depth, but deep nesting combined with mixin expansion creates a combinatorial explosion of selectors. This reduces readability and increases the risk of specificity conflicts, as the compiled output often results in long, overly-specific selector chains.
Verification Steps
To determine if a mixin is causing excessive bloat, perform a manual audit of the compiled output:
- Compile the Stylus file to a temporary CSS file.
- Search for repeated property-value pairs that appear across different selectors.
- Compare the file size of the current output against a version where the mixin is replaced by a single utility class.
Diagnostic Detail Needed: To provide a more specific refactoring recommendation, please provide the average number of selectors calling your most-used mixin and whether the arguments passed to those calls are typically identical or unique.