Loops and Mixed Nesting in Stylus
Stylus, as a powerful CSS preprocessor, stands out for introducing JavaScript-like variables, functions, and loop structures. Among these, "loops" are one of the key tools for constructing complex styling logic. Unlike traditional Sass (SCSS), Stylus supports for statements to iterate over arrays or object collections, thereby generating repetitive code blocks. Mastering this feature can greatly simplify tasks involving list items, grid layouts, or multi-variant designs, reducing the amount of redundant code required.
When executing loops in Stylus, it is essential to explicitly specify the iteration variable and its range. The syntax structure typically follows the for (var in range) { ... } pattern. Here, range can be a numeric interval (such as 0 to 10), or a string collection or list of object keys. Understanding this fundamental mechanism is a prerequisite for mastering mixed nesting logic, as loops often need to be combined with conditional statements and block-level selectors to achieve dynamic style generation.
The most direct application of looping is in scenarios involving numeric iteration. Suppose we need to set different background colors or font sizes for a series of elements numbered from 1 to 5. Using the for statement, we can easily automate the processing of these styling rules.
#container
&.item:nth-child(#{i + 1})
background-color: rgb(i * 20, i * 30, i * 40)
font-size: (i + 1)rem
for i in range 5 to 6 do
In the example above, range 5 to 6 defines an integer sequence from 5 to 6 (inclusive). The variable i is referenced within the loop body to dynamically calculate the RGB values for the background color and the unit for the font size. This approach not only avoids manually writing multiple .item:nth-child(...) rules but also enhances code maintainability. When adjusting the color scheme or spacing, simply modifying the generation logic will automatically update all relevant styles.
Iterating Over String Arrays and Object Keys
In addition to numeric loops, Stylus also supports iterating over string lists and object properties. This is particularly useful when handling internationalized interfaces (i18n) or multi-theme switching scenarios. For instance, if there is a color mapping table containing different text colors, we can use the for statement combined with variable destructuring to generate corresponding class names or style rules.
colors = { red: "#ff0000", green: "#008000", blue: "#0000ff" }
#text-wrapper
for color in colors do
&.color-#{key}
color: value
for key, value in colors do
The second writing style demonstrates a more general object iteration method, where key and value represent the object's key name and value respectively. The CSS classes generated in this manner (such as .color-red, .color-green) can be directly applied to HTML elements for dynamic color styling. This pattern breaks the limitations found in traditional SCSS regarding direct manipulation of complex data structures, highlighting Stylus's flexibility as a JavaScript-like preprocessor.
Mastering the Combination of Mixed Nesting and Conditional Logic
The true power of loops lies in their ability to be deeply combined with "block-level selectors" and "conditional statements (if/else)", forming what is known as mixed nesting structures. This means we can define multiple levels of parent-child relationships within a single for block and execute branch logic based on different iteration values. This capability allows Stylus to simulate the functionality of dynamic layout generators similar to CSS Grid or Flexbox.
#grid-container
for i in range 1 to 4 do
&.cell-#{i}
display: flex
if (i % 2 == 0) then
justify-content: center
else
align-items: center
for item in ["left", "right"] do
#sidebar-item:nth-child(#{item})
In this example, the outer loop generates four grid cells (.cell-1 to .cell-4), while an internal if/else judgment sets different Flexbox properties based on parity. Simultaneously, another independent loop handles different alignment methods for the sidebar. This multi-level nested structure enables developers to write highly customized layout logic without relying on external JavaScript libraries or complex CSS Grid template syntax (although Stylus itself does not directly support Grid Template Syntax, it can simulate some effects through variables and functions).
Best Practices and Performance Considerations
Although loop functionality is powerful, code readability and execution efficiency must still be considered in actual projects. First, avoid performing heavy computations or DOM operations inside loops, as the final CSS generated by preprocessors is static, and browsers do not re-parse this logic; second, extract constants to variables as much as possible to reduce repetitive string concatenation; finally, keep nesting levels no more than three to ensure the generated CSS structure is clear and easy to understand.
Furthermore, since Stylus's loop syntax borrows from JavaScript style, developers should be familiar with its scope rules to prevent accidentally modifying values of externally defined variables. Reasonably utilizing keywords like let and const can effectively isolate local states, enhancing code robustness. Through these practical methods, loops and mixed nesting techniques in Stylus will become an indispensable tool for building modern responsive web applications.