How to Generate a Gradient for your CSS using RMagick

October 21, 2008

I find it’s painful to go back to Photoshop just to generate a gradient, especially when I’m modifying the CSS at the very same time to find the right colors.

Here’s the Rake task I use now to quickly generate a gradient background:

desc "Generate the gradient background" 
task :gradient do
  require 'rmagick'
  include Magick

  WIDTH = 1
  HEIGHT = 154

  gradient = GradientFill.new(
    0, 0, WIDTH, 0, "#84704E", "#99906E")
  image = Image.new(WIDTH, HEIGHT, gradient)
  image.write("images/gradient.jpg")
end

I put this code under version control, in a Rakefile placed inside the Mephisto (in this case) theme itself.

The corresponding CSS contains:

body {
    padding: 0em;
    margin: 0em;
    color: #333333;
    font-family: "Helvetica Neue", Helvetica,
                 Arial, Sans-Serif;
    background: #99906E
                url(../images/gradient.jpg) repeat-x;
}

If I need to DRY things out, it’s possible to extract the body background color from the CSS, to use it in the GradientFill.new call:

background_color = IO.read("stylesheets/main.css")
  .grep(/background:#([\S]+)/) { $1 }
gradient = GradientFill.new(
  0, 0, WIDTH, 0, "#84704E", background_color)

Alternatively if you generate your CSS with SASS you could tap into the SASS source directly.

That’s it. I’ve used this on the blog you’re currently reading and also on my mind-mapping and self-improvement blog.

I’ll experiment more with shadows and other little customizations when required.