Sass math.random() Function

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
sass:math · Other Functions

What You’ll Learn

math.random() is a compile-time random helper in the sass:math module. You will learn both call shapes (decimal vs integer), the global random() alias, why values freeze into CSS, the deprecated unit-ignoring caveat on $limit, and five examples.

01

Concept

Random numbers

02

Module

@use "sass:math"

03

No args

0 … 1 decimal

04

With limit

1 … N integer

05

When

Compile time

06

Practice

5 examples

What Is math.random()?

Sometimes you want variety baked into generated CSS—slightly different opacities, random order values, or demo noise. Sass can roll those numbers while compiling. Official docs place math.random under Other Functions.

  • math.random() → random decimal between 0 and 1 (exclusive of exact predictability)
  • math.random(10) → random whole number from 1 to 10
  • Each call / each compile can produce a different result
💡
Beginner tip

Think of it as a dice roll during the build. Once CSS is written, the number is fixed until you compile again. It will not keep changing in the browser.

📝 Syntax

Load the math module, then call the function:

styles.scss
@use "sass:math";

math.random($limit: null)

Parameters

ParameterTypeRequiredDescription
$limitNumber or nullNo (default null)If omitted/null: return a decimal in [0, 1)-style range. If a number ≥ 1: return a whole number from 1 to that limit.

Return value

CallReturns
math.random()Random unitless decimal between 0 and 1
math.random($limit) with $limit ≥ 1Random whole number from 1 to $limit (inclusive)

📦 Loading sass:math

Prefer the module API. Official docs also document a global name, random(), for older stylesheets.

styles.scss
// Recommended — namespaced
@use "sass:math";
$n: math.random();
$i: math.random(10);

// Optional — bring members into the current namespace
@use "sass:math" as *;
$n: random();

// Optional — custom namespace
@use "sass:math" as m;
$n: m.random(5);

// Legacy global name (still works in many setups)
$n: random(5);

📏 Limits, Units, and Deprecation

Pass a plain integer when you want 1…N. Official docs warn about units on $limit:

⚠️
Heads up from the docs

Today, math.random($limit) ignores units on $limit (so math.random(100px) acts like math.random(100) and returns a unitless integer). That behavior is deprecated. In a future Sass release, the result will keep the same units as $limit. Prefer unitless limits like math.random(100) in new code.

CallTypical result shapeNotes
math.random()0.2821251858 (example)Decimal between 0 and 1
math.random(10)4 (example)Integer 1–10
math.random(10000)5373 (example)Integer 1–10000
math.random(100px)Unitless int today + warningDeprecated unit-ignore path—avoid

🛠 Compatibility

This is about Sass compilers, not browsers. The random value is chosen while compiling—browsers only see the finished number.

Implementationmath.random()Notes
Dart Sass (modules)YesUse @use "sass:math" (about 1.23+)
Global random()Yes (legacy name)Same idea; prefer the module form in new code
LibSass / Ruby SassNo module APIMay still expose global random(); prefer Dart Sass

⚡ Quick Reference

GoalCode
Import math@use "sass:math";
Random fractionmath.random()
Random integer 1–Nmath.random(10)
Reuse one roll$n: math.random(5); then use $n twice
Safe limit stylemath.random(100) (unitless)
Avoidmath.random(100px) (deprecated unit ignore)
Legacy globalrandom(10)
Debug while learning@debug math.random(10);

📋 Sass math.random() vs JS Math.random()

Sass math.random()JS Math.random()
When it runsCompile time (Dart Sass)In the browser / Node
Appears in CSS?Only the finished numberNot in CSS unless you inject it
Changes on refresh?Only after you rebuild CSSYes, every script run
Best forBuild-time variety / demosLive interaction & animation

Examples Gallery

Each example uses @use "sass:math". Open View Compiled CSS for a sample output—your next compile will likely show different numbers.

📚 Getting Started

Official-style decimals and integers from the Sass docs.

Example 1 — Basic math.random()

No argument → a random decimal between 0 and 1.

styles.scss
@use "sass:math";

@debug math.random(); // e.g. 0.2821251858
@debug math.random(); // e.g. 0.6221325814

.fade {
  opacity: math.random();
}

How It Works

Each call draws a new decimal. The sample CSS above is one possible compile result; yours will differ.

Example 2 — Integer Limit

Pass a number ≥ 1 to get a whole number in that range.

styles.scss
@use "sass:math";

@debug math.random(10);    // e.g. 4
@debug math.random(10000); // e.g. 5373

.card {
  z-index: math.random(10);
}

How It Works

math.random(10) returns an integer from 1 through 10 inclusive—useful for discrete layers, orders, or demo IDs.

📈 Practical Patterns

Reuse one roll, build playful layouts, and avoid the unit trap.

Example 3 — Store One Roll

Save the result if several properties should share the same random value.

styles.scss
@use "sass:math";

$roll: math.random(5);

.tile {
  order: $roll;
  z-index: $roll;
}

How It Works

Calling math.random twice would usually give two different numbers. Storing $roll keeps order and z-index in sync.

Example 4 — Soft Random Accent

Blend a fraction into a design token for subtle build-time variety.

styles.scss
@use "sass:math";

$jitter: math.random(); // 0…1

.badge {
  opacity: 0.7 + $jitter * 0.25; // about 0.7–0.95
  letter-spacing: #{0.02 + $jitter * 0.04}em;
}

How It Works

One stored fraction scales both opacity and tracking. Great for static demos; not for live motion.

Example 5 — Prefer Unitless Limits

Avoid passing units into $limit—that path is deprecated.

styles.scss
@use "sass:math";

// Avoid (warns: units currently ignored)
// $bad: math.random(100px);

// Prefer unitless limit, then attach units yourself if needed
$steps: math.random(8);
.spacer {
  margin-block: #{$steps * 4}px; // 4px…32px in 4px steps
}

How It Works

Roll a unitless integer, then multiply by a step size. You stay future-safe when Sass stops ignoring units on $limit.

🚀 Real-World Use Cases

  • Demo / marketing builds — slightly different opacities or orders each release.
  • Placeholder galleries — random order / z-index for masonry-like tests.
  • Design exploration — quick noise while prototyping tokens.
  • Seeded-looking variety — store one roll and derive several properties from it.
  • Teaching compile time — show that Sass numbers freeze into CSS.
  • Not for live UX — use JavaScript when randomness must change after load.

🧠 How Compilation Works

1

Write SCSS

Call math.random() or math.random($limit) after @use.

Source
2

Draw a value

Sass picks a decimal or an integer in range during the build.

Randomize
3

Substitute into CSS

The chosen number is written into properties and custom props.

Emit
4

Static CSS ships

Browsers never re-roll math.random.

⚠️ Common Pitfalls

  • Expecting runtime changes — rebuild CSS to get new numbers.
  • Calling twice by accident — store one result when values must match.
  • Passing units to $limit — deprecated ignore-units behavior; use unitless limits.
  • Limits below 1 — the integer form expects $limit ≥ 1.
  • Using it for secure tokens — this is styling noise, not cryptography.

💡 Best Practices

✅ Do

  • Use @use "sass:math" and math.random() in new SCSS
  • Pass unitless integer limits
  • Store rolls in variables when sharing across properties
  • Use JS random for live interaction
  • Prefer Dart Sass for the modern module API

❌ Don’t

  • Pass px/em limits (deprecated path)
  • Assume the browser keeps re-rolling
  • Rely on LibSass for sass:math
  • Use Sass random for security or unique IDs across users
  • Forget that CI rebuilds can change snapshot CSS

Key Takeaways

Knowledge Unlocked

Five things to remember about math.random()

Compile-time dice—decimals or 1…N integers.

5
Core concepts
📦 02

Module

sass:math

@use
🎲 03

No args

0…1 decimal

Range
04

With n

1…n integer

Limit
05

When

compile time

Sass

❓ Frequently Asked Questions

With no argument, math.random() returns a random decimal between 0 and 1. With math.random($limit) where $limit is a number ≥ 1, it returns a random whole number between 1 and $limit inclusive.
Add @use "sass:math"; then call math.random() or math.random(10). Prefer the module form in new SCSS. The global alias is random().
Yes, each call can produce a new value when Sass compiles. Recompiling the same file usually changes the CSS numbers. It is not a browser runtime random function.
Official docs say random currently ignores units on $limit (so 100px behaves like 100). That unit-ignoring behavior is deprecated; a future release will return a random integer that keeps the same units as $limit.
No. Sass random is fixed when CSS is generated. For values that change while the page runs, use JavaScript Math.random() or CSS features that resolve in the browser.
Built-in modules with @use need Dart Sass (about 1.23+). Older setups can still call the global random() name. LibSass and Ruby Sass do not load sass:math the same way.
Did you know?

Official Sass docs list math.random under Other Functions and warn that ignoring units on $limit is deprecated. Future Sass will return a random integer that keeps those units—another reason to pass unitless limits today.

Conclusion

math.random() rolls decimals (0–1) or integers (1–N) while Sass compiles. Keep limits unitless, store shared rolls in variables, and use JavaScript when randomness must continue after the page loads.

Continue with math.round(), math.percentage(), or math.pow().

More Sass Math

Continue with nearest-integer rounding in the math module.

math.round() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful