I'm working on a project where I utilize SASS and Compass and need to somehow come up with some random numbers in the CSS file. Specifically, I need some floating point numbers between 0 and 1. Is this possible with SASS and Compass alone?
This is very possible if you create a sass function since sass is ruby its as easy as opening the functions module and injecting your random function
module Sass::Script::Functions
module MyRandom
def random
rand(1.0)
end
end
include MyRandom
end
require the file after sass has loaded
Then in your stylesheet
$my-randome-number: random();
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 first I did not know where to place the Code and then it did not work. I had to play around with the snipped and expanded it to more Flexibility that I had need for:
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 a SCSS file like this:
@debug usw_random();
@debug usw_random(10);
@debug usw_random(8, 2);
@debug usw_randomColor();
and will printout:
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 within compass framework. You can place this Code directly into your Compass Config.rb file.
Or you put it in another file and only put this line into your Compass Config.rb file:
## my "own" ruby functions.
require "../SASS/RUBY/at.usw.rb"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With