Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number within a min and max parameters in SASS?

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!

like image 885
Serhii Borovskyi Avatar asked Dec 12 '16 07:12

Serhii Borovskyi


2 Answers

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

like image 158
Raviteja Avatar answered Sep 28 '22 11:09

Raviteja


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.

like image 37
3rdthemagical Avatar answered Sep 28 '22 10:09

3rdthemagical