Generating random color in Sass

I needed to generate HTML elements which had random background colors with Sass. Unfortunately, it’s absolutely impossible.

So, I decided to add a custom ruby method to the Sass::Script::Functions module. It’s incredibly elementary but maybe it’ll help someone :)

So, here is the code. You can put it in your config.rb for example.

module Sass::Script::Functions
    def getRandomColor()
        Sass::Script::String.new("#%06x" % (rand * 0xffffff))
    end
end

Usage

@for $i from 1 through $len {
    .item-#{$i} {
        background:getRandomColor();
    }
}

  • marat

    Куда надо добавлять данное раширение, чтобы заработало в rails 3.2.8 ? там ведь не существует config.rb

    • http://twitter.com/_victa Victor ☃

      English?

    • http://twitter.com/holek_ Mike Połtyn

      Create config/initializers/css_random_color.rb and add it there.

  • yuvilio

    I found that when using this inside another function that required the color to NOT be a string, I got an error. for example:


    body {
    background: lighten(getRandomColor() ,20%) ;
    }

    coomplained:

    Syntax error: "#20b6b6" is not a color for `lighten'

    After a little googling, I found you can alternately use the Sass::Script::Color object in those cases. Rewrote your method to offer both choices:


    def getRandomColor(as_str = false)
    if as_str
    Sass::Script::String.new("#%06x" % (rand * 0xffffff))
    else
    Sass::Script::Color.new([rand(255), rand(255), rand(255)])
    end
    end

    can now be invoked with getRandomColor() or getRandomColor(false) inside the sass.

    • http://twitter.com/_victa Victor ☃

      Nice! Thanks for sharing!