How to generate a random number within a min and m

2020-07-06 05:53发布

How to generate a random number within a min and max parameters in SASS? For example a random number from 5 to 15.

.foo
  font-size: random(15)#{px}

If that is not possible, what would be a similar formula?

Thank you!

2条回答
男人必须洒脱
2楼-- · 2020-07-06 06:29

There is no minimum value to set in SASS.

But you can tweak it as follows for a random number from 5 to 15.

.foo
  font-size: (random(11) + 4)+px

added 4 to 11, because random() function has minimum value of 1

查看更多
神经病院院长
3楼-- · 2020-07-06 06:29

There is a standard pattern to generate random value in a range.

Min + (int)(Math.random() * ((Max - Min) + 1))

In scss it would look like:

@function randomNum($min, $max) {
  $rand: random();
  $randomNum: $min + floor($rand * (($max - $min) + 1));

  @return $randomNum;
}

.foo {
  font-size: #{randomNum(5, 10)}px;
}

Sassmeister demo.

查看更多
登录 后发表回答