Super-easy cross-browser gradient backgrounds

Posted by Tom on 2009-06-23

screen shot

Hobo 0.8.8 is coming very soon, consisting mostly of bug fixes and bringing us that bit closer to the hallowed version 1.0. While we’re waiting, I though I’d quickly let you know about a very simple Rails plugin I knocked up that makes it extremely easy to add gradient background images to your stylesheets. (If you follow the hobousers group you’ve already seen a mention of this.)

For example:

div.featured { background: url(/gradient_images/50:aaa:fff.png) repeat-x white; }

All that’s happening is that the plugin is rendering a PNG image on the fly; 1 pixel wide, 50 high, with a gradient from a light grey (#aaa) to white. It renders the image you would otherwise have to make yourself in Photoshop or whatever.

The general pattern for the image URL is:

/gradient_images/<height>:<start-color>:<end-color>.<format>

Colours are 3 or 6 digit hex values, as in CSS. The format can be anything supported by ImageMagick (e.g. png or jpg).

You can also do multiple gradients in the same image, like this

div.featured {
  height: 100px;
  background: url(/gradient_images/50:aaa:fff::50:fff:aaa.png) repeat-x 
}

That will give an image 100 pixels high fading from grey to white and back to grey.

Note that you only take the performance hit on the first request, after that the images will be served up directly by your web server thanks to Rails’ page caching. You’ll see a bunch of image files in public/gradient_images.

Requires Rails 2.3 and RMagick.

The plugin is available on github.

UPDATE: We just threw up a quick example app on github. It’s great to see how much nicer you can make the default Hobo app look with just three CSS declarations.



(edit)