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

与世无争的帅哥 提交于 2020-02-27 05:19:19

问题


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!


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/41096204/how-to-generate-a-random-number-within-a-min-and-max-parameters-in-sass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!