Can I create random numbers in SASS / Compass?

I am working on a project in which I use SASS and Compass, and you need to come up with some random numbers in the CSS file somehow. In particular, I need some floating point numbers between 0 and 1. Is this possible with SASS and Compass?

+4
source share
3 answers

This is very possible if you create a sass function, since sass ruby โ€‹โ€‹is as simple as opening a function module and entering your random function

module Sass::Script::Functions module MyRandom def random rand(1.0) end end include MyRandom end 

file required after loading sass

Then in your stylesheet

 $my-randome-number: random(); 
+9
source

Yes, as Scott said, it is possible, but I am not a Rails programmer, so I just wanted to copy and paste the code, but at first I did not know where to place the code, and then it does not work. I had to play with a margin and expand it to the more flexibility I need:

 module Sass::Script::Functions module USW_Random ## Create random Color # inspired by: http://victorcoulon.fr/generating-random-color-in-sass/ # def usw_randomColor() Sass::Script::Color.new([rand(255), rand(255), rand(255)]) end ## Create random Number # int max [optional] if max is not supplied a float between 0 and 1 is returned. # if max is supplied, an Integer between 0 and max (both inclusive) will be returned. # int min [optional] if min is supplied too, an Integer between min and max (both inclusive) will be returned. # def usw_random(max=-1, min=0) Sass::Script::Number.new( max.to_i < 0 ? rand() : rand(min.to_i .. max.to_i )) end end include USW_Random end 

Ths can be used in the SCSS file as follows:

 @debug usw_random(); @debug usw_random(10); @debug usw_random(8, 2); @debug usw_randomColor(); 

and prints:

 xxx.scss:25 DEBUG: 0.42782 xxx.scss:26 DEBUG: 3 xxx.scss:27 DEBUG: 5 xxx.scss:28 DEBUG: #e7c00b 

I also did not know where to put the code for this. I use SASS as part of a compass. You can place this code directly in the Compass Config.rb file.

Or you put it in another file and put this line in your Compass Config.rb file:

 ## my "own" ruby functions. require "../SASS/RUBY/at.usw.rb" 
+3
source

Update: Sass 3.3 (2014) now has a built-in random() function:
http://sass-lang.com/documentation/Sass/Script/Functions.html#random-instance_method

 $number: random() 

You can also create your own simple serialized random function in Sass. Example (SCSS):

 /* YOUR SEED HERE: */ $seed: 369; @function getRandom($max) { //http://indiegamr.com/generate-repeatable-random-numbers-in-js/ //Note the "!global" flag: //http://webdesign.tutsplus.com/articles/understanding-variable-scope-in-sass--cms-23498 $seed: ($seed * 9301 + 49297) % 233280 !global; @return ($seed / 233280) * $max; } .my-class { height: getRandom(200) + px; opacity: getRandom(1); } 

http://codepen.io/Sphinxxxx/pen/Gpmmye

+1
source

Source: https://habr.com/ru/post/1387900/


All Articles