How to add a gradient in css

This is a really simple way to add a gradient to any html element. Note that newer webkit based browers have built in support for the -webkit-gradient property, and the latest and greatest versions of firefox and IE each have their own methods of easily generating gradients. The method I show here requires you to create a gif, which is a disadvantage, but you don’t have to worry about the bane of front end development – cross browser support and backwards comptability.

The process is relatively simple. The first step is to create a 1 pixel wide gif of a gradient. The second step is of course, to modify the css.

If you’re not a photoshop pro or don’t own photoshop, don’t worry. Its relatively simple to create a gradient (and free!). You can use the open source GIMP. What you’ll want to do is create a new image, with 1 pixel width and whatever height (Increase zoom by going to View-> Zoom). Now select the Blend Tool (selected in the screenshot below). The two color points of the gradient are set by the Foreground/Background colors selector.

In this example, I created one that goes from a randomly selected shade of red to yet another randomly chosen shade of blue (an artist I am not, so I sadly do not know the name of more than a dozen colors). Use the blend tool to apply the gradient, save the image, and you’re almost done!

Once you have the gif, you can add a gradient class to your css. The trick is to set the background-image to that of the gradient image, and then to use the repeat-x value of the background-repeat property so that the gif spans the entire element.

gradient {
background-image: url(redbluegradient.gif);
background-repeat: repeat-x;

Note the background-color is set to #5b7ad1, which was the end color of the gradient. This way, if your element height is larger than that of the gradient image (if for example, you want the gradient as the background for the entire page), it will end up transitioning smoothly.