Conditional Logic and Mixed Parameterization in Stylus

Conditional Logic and Mixed Parameterization in Stylus

In the Stylus CSS preprocessor, conditional logic is a key mechanism for building dynamic styling rules. It allows developers to generate different CSS rules based on runtime data or compile-time variables, significantly enhancing flexibility and maintainability. Similar to Sass's if statements, Stylus offers powerful support for conditional expressions, but it possesses unique advantages when handling complex logic and nested structures. Mastering this mechanism enables developers to implement everything from simple color switches to high-dimensional responsive layout adjustments.
Stylus conditionals follow the standard if (condition) { block } else { block } format. The compiler first evaluates the boolean expression within the parentheses; if the result is truthy, it executes the corresponding code block, otherwise it skips to the else branch. Notably, Stylus supports various comparison operators, including ==, !=, >, <, >=, and <=, as well as logical operators && and ||.

// Basic example: determining color based on variable value
bg-color = '#3498db'
if isDarkMode
  bg-color = '#2c3e50'
else
  bg-color = '#ecf0f1'

body
  background: bg-color

In the code above, isDarkMode is typically a boolean variable or an object property. When this condition is true, the background color is updated to the dark theme; otherwise, it remains light. This mechanism allows styles to easily adapt to different environment configurations.

Nested Conditionals and Logical Combinations

In actual development, a single conditional often fails to cover all scenarios, making nested conditionals and logical combinations common requirements. Stylus allows defining new conditional judgments inside an if block, forming a multi-layer decision tree. Furthermore, by combining && and || operators, developers can construct more complex filtering logic without introducing additional variables to perform multi-step judgments.

user = { role: 'admin', hasPremium: true }

if user.role == 'admin' && user.hasPremium
  header
    background: '#f39c12'
    border-radius: 5px
  aside
    display: block
else if user.role == 'guest'
  footer
    padding: 20px
  aside
    display: none

This code demonstrates how to dynamically control DOM structure based on a combination of user role and permission checks. When the user is both an administrator and has premium access, the header area receives special styling and the sidebar is displayed; if the user is merely a guest, the sidebar is hidden and the footer padding is adjusted. This logic maps directly to the final CSS output, reducing redundancy from intermediate variables.

Efficient Application of Ternary Operators

In addition to traditional if-else structures, Stylus also supports the ternary operator ? :, which is particularly practical when concise expression of simple conditional logic is required. The ternary operator returns a value rather than executing a code block and is commonly used for initializing variables or setting simple style properties.

font-size = '16px'
if screenWidth > 768
  font-size = '20px'
else
  font-size = '14px'

// Using ternary operator to simplify font size setting
fontSize = screenWidth > 768 ? '20px' : '14px'

body
  font-size: fontSize

While ternary operators are less flexible than if-else in complex logic scenarios, they can significantly reduce code lines and improve readability when handling single-value assignments or simple conditional branches. Developers should select the most appropriate syntax form based on specific scenarios.

Mixed Parameterization and Dynamic Property Names

A major feature of Stylus is its mixed parameterization capability, which allows using variables directly as property names, values, or even parts of nested structures within CSS. Combined with conditionals, this enables highly customized style output. For example, it can dynamically generate class names with specific prefixes or custom properties based on conditions.

prefix = 'mobile'
if device == 'phone'
  prefix = 'touch'

.container
  &.#{prefix}-layout
    padding: 10px
    margin: auto

// Dynamic property example
if supportsTouch
  body
    touch-action: pan-y

In such scenarios, the #{} syntax is used to interpolate variables, allowing the generated CSS to adapt to different device characteristics. When touch support is detected, the body element automatically receives the touch-action property, optimizing the scrolling experience. This flexibility is unmatched by traditional CSS.

Best Practices and Performance Considerations

When using conditionals, follow these principles to ensure code quality and compilation efficiency:

  • Prioritize simple, explicit boolean conditions and avoid excessive nesting;
  • Extract frequently changing logic into independent functions or modules for easier reuse;
  • Pay attention to Stylus's compilation order, as complex conditions may affect dependency resolution speed;
  • For performance-sensitive scenarios, strive to complete judgments at compile time rather than relying on runtime data.

By reasonably applying conditional logic and mixed parameterization techniques, Stylus can help developers build modern styling systems that are both flexible and efficient. Whether dealing with multi-device adaptation or dynamic theme switching, these tools provide powerful support.