DEV Community

Cover image for 🔥 CSS Generate Random UI Boxes (FSCSS)
FSCSS tutorial
FSCSS tutorial

Posted on • Edited on

🔥 CSS Generate Random UI Boxes (FSCSS)

I just hit a fscss fun milestone… It can generate dynamic UI styles using arrays, functions, and a bit of randomness. 😅

âš¡ Example

@arr spacing[
    count(5,1)
]

@arr indexes[
    count(5)
]

$m-spacing: @arr.spacing!;

@define boxes(){`
.box-@arr.indexes[]{
  $i: @arr.indexes[];

  background: #2c5364;
  margin: $spacing[$i]px;

  %2(width, height [: num($m-spacing.randint * 20)px;])
}
`}

@boxes()
Enter fullscreen mode Exit fullscreen mode

🤯 What This Does

  • Generates classes: Creates .box-1 through .box-5 automatically.
  • Unique Attributes: Each box receives a different margin and a random width/height.
  • Zero JS: Purely compiled via FSCSS logic.

The Magic

  • $m-spacing.randint: Picks a random value from the defined array.
  • num(... )px: Handles safe mathematical calculations for units.
  • %2(width, height [...]): A shorthand to assign the same generated value to multiple properties simultaneously.

Why This Matters

Instead of writing repetitive, hard-coded CSS, you describe the rules and let FSCSS handle the heavy lifting. It brings programmatic logic to styling without the overhead of a runtime library.
Bonus (Layout)

.container {
  @flex-responsive(20px)
}
Enter fullscreen mode Exit fullscreen mode

The Full Implementation

If this looks interesting, I might share more! Here is a look at a full implementation involving color arrays and responsive containers:

@import((flex-responsive) from flex-control)

$primary-color: #3498db;
$secondary-color: #2ecc71;
$font-family: 'Arial', sans-serif;
$colors: @arr.colors;
$m-colors: @arr.colors!;
$spacing: @arr.spacing;
$m-spacing: @arr.spacing!;
$num-ranges: 5,0.2;

@arr colors[
    #2c5364, 
    #1E2783, 
    #555111,
    #EECDA3, 
    #EF629F,
]

@arr spacing[
    count(5,1)
] 

@arr indexes[
    count(5)
]

body {
    font-family: $font-family;
    max-width: 100vw;
    min-height: 100vh;
    overflow-x: hidden;
    overflow-y: auto;
}

@define color-box-base(){`
.color-@arr.indexes[]{
    $i: @arr.indexes[];
    background-color: $colors[$i];
    margin: $spacing[$i]px;
    border: 2px solid $m-colors.randint;
    %2(width, height [: num($m-spacing.randint * 20)px;])
}
`} 

.container {
    @flex-responsive(20px)
}

@color-box-base()
Enter fullscreen mode Exit fullscreen mode

fscss highlight looks better on vscode

What do you think?

Top comments (0)