DEV Community

Cover image for FSCSS Loop: Styling 36 Elements Without Writing 36 Rules
FSCSS for FSCSS tutorial

Posted on

FSCSS Loop: Styling 36 Elements Without Writing 36 Rules

In regular CSS, styling multiple elements individually means writing a rule for each one. nth-child(1), nth-child(2)... all the way down. That's repetitive, brittle, and just not fun.

FSCSS solves this with arrays and loops — no mixins needed.


The Demo

36 dots. 36 different colors. One loop.


How It Works

Step 1 — generate values with count()

@arr i[count(36, 10)]
Enter fullscreen mode Exit fullscreen mode

count(36, 10) generates 36 values starting from 10, incrementing by 10 each time:
10, 20, 30, 40 ... 360

⚠️ Note: the sequence starts at 10, not 0. count(n, step) begins at step, not zero.

Step 2 — loop with @arr.name[]

.orbit .dot:nth-child(@arr.i[]) {
  $i: @arr.i[];

  background: hsl($i, 100%, 60%);
  transform: rotate($i!deg) translateX(120px);
  %2(width, height[: 50px;])
  position: absolute;
}
Enter fullscreen mode Exit fullscreen mode

@arr.i[] inside a selector expands into every nth-child index — starting from 1, matching CSS's own 1-based nth-child counting. Each iteration binds the current value to $i, which gets used for both the hue and the rotation angle.

So dot #1 gets hsl(10, 100%, 60%) rotated 10deg. Dot #2 gets hsl(20, 100%, 60%) rotated 20deg. All the way to 360deg — a full rainbow orbit.


What this replaces

Without FSCSS, you'd write something like:

.orbit .dot:nth-child(1)  { background: hsl(10,  100%, 60%); transform: rotate(10deg)  translateX(120px); }
.orbit .dot:nth-child(2)  { background: hsl(20,  100%, 60%); transform: rotate(20deg)  translateX(120px); }
/* ... 34 more lines */
.orbit .dot:nth-child(36) { background: hsl(360, 100%, 60%); transform: rotate(360deg) translateX(120px); }
Enter fullscreen mode Exit fullscreen mode

That's 36 rules written by hand — and if you want to change the radius, you touch 36 lines.

With FSCSS, it's one block. Change 120px once, done.


Key things to know

  • count(n, step) starts at step, not 0. count(36, 10)10, 20, 30 ... 360
  • @arr.name[] in a selector loops the whole rule block per value
  • @arr.name[] in a value outputs the current iteration's value
  • nth-child indexing is 1-based in both CSS and FSCSS arrays — they align naturally
  • For testing No build step — use FSCSS runtime via jsdelivr
<script src="https://cdn.jsdelivr.net/npm/fscss@1.1.24/exec.min.js" async></script>
Enter fullscreen mode Exit fullscreen mode

Docs

Array reference → fscss.devtem.org/arrays


Top comments (0)