DEV Community

Cover image for Styling Deeply Nested divs with One FSCSS Array Loop (No More Hand-Writing Selectors)
FSCSS tutorial for FSCSS tutorial

Posted on Originally published at fscss.devtem.org

Styling Deeply Nested divs with One FSCSS Array Loop (No More Hand-Writing Selectors)

Writing nested selectors by hand is painful.

div { background: orange; }
div div { background: purple; }
div div div { background: indigo; }
/* …and it gets worse the deeper you go */
Enter fullscreen mode Exit fullscreen mode

FSCSS gives us a clean way to generate the entire chain in a single loop using @arr + rpt().

The Problem

You have a simple nested structure:

<div>1
  <div>2
    <div>3</div>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

You want each level to have a different background color (and maybe padding, border-radius, etc.) without writing the selectors manually.

The One-Loop Solution

<script src="https://cdn.jsdelivr.net/npm/fscss@1.2.0/runtime.min.js" async></script>

<style>
@arr colors[orange, purple, indigo]
@arr levels[count(3, 1)]          /* → 1, 2, 3 */

rpt(@arr.levels[], "div ") {      /* builds "div ", "div div ", "div div div " */
  background: @arr.colors[@arr.levels[]];
  padding: 10px;
  border-radius: 10px;
  color: #fff;
  margin: 8px;
}
</style>
Enter fullscreen mode Exit fullscreen mode

That’s it.

What Gets Generated

div {
  background: orange;
  padding: 10px;
  border-radius: 10px;
  color: #fff;
  margin: 8px;
}

div div {
  background: purple;
  /* same properties */
}

div div div {
  background: indigo;
  /* same properties */
}
Enter fullscreen mode Exit fullscreen mode

How It Works

  1. @arr levels[count(3, 1)] creates the numbers 1, 2, 3.
  2. rpt(@arr.levels[], "div ") repeats the string "div " according to the current level.
  3. Inside the rule, @arr.colors[@arr.levels[]] picks the matching color (arrays are 1-indexed).
  4. FSCSS expands the whole block once for every item in the array — one clean loop.

Easy Variations

Change depth

Just update the count() and the colors array:

@arr colors[tomato, coral, salmon, crimson]
@arr levels[count(4, 1)]
Enter fullscreen mode Exit fullscreen mode

Use child combinator instead of descendant

rpt(@arr.levels[], "div > ") {
  /* now generates div >, div > div >, etc. */
}
Enter fullscreen mode Exit fullscreen mode

Add more properties or even different values per level

You can reference the level index for anything — font-size, opacity, animation-delay, etc.

Why This Feels Good

  • Zero repetitive typing
  • Depth and colors stay in sync
  • Still pure CSS after compilation
  • Works with the browser runtime or the CLI

Hand-writing nested selectors used to be a small but annoying chore. With FSCSS arrays + rpt(), it becomes a one-liner pattern you can reuse anytime.

Full: https://fscss.devtem.org/nested-loop

Top comments (0)