Webistrate - Draw Your Own Conclusions

CSS3: Creating a Background Gradient

Posted by Jamie Munro | January 23, 2012 | Tags:

Share

Do you see the gradient blue above for the title of this article?  If you don’t then your browser doesn’t support CSS3 gradients.  However, if you do see it, you’ll be happy to know that I saved you and me some bandwidth by not using an image!  Instead, some CSS3 is used.  So next time a designer provides you a PSD with a bunch of gradient images forget “chopping” them out and use the following example instead.

 To create a gradient background image, you need two things: a starting color and a bottom color.  It would also be handy to have a potential “fall back” background color that sits somewhere in the middle of the two.

For the purpose of this example, here is the start HEX color value: #12496f and here is the end HEX color value: #1e70aa.  The fall back background color will be: #185c8c.  Now that I have my colors, here is the CSS required to create a gradient background.  In the following example, I want the background color to appear for my header 2 tags (the title of my articles).

h2 {
background: #185c8c;
background-image: -moz-linear-gradient(top, #12496f, #1e70aa);
background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #12496f),color-stop(1, #1e70aa));
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#CC12496f, endColorstr=#CC1e70aa);

padding: 6px;
color: #FFF;
}

As you might notice in the above example, the start and end colors are repeated three times.  The reason for this is that each of the major browsers implement gradients in a different fashion and our CSS pays the price for it and we need to include each of the types.

I’m sure you guessed which browser each is for, but in case not, the first one: -moz-linear-gradient is for Firefox and other Mozilla based browsers.  The second one: -webkit-gradient, is for webkit based browsers such as Google Chrome and Safari.  The third one is for Internet Explorer where a DXImageTransform function is used to create the gradient.

Summary

The next time a designer decides that a gradient should be used for a background image, have no fear because you no longer need to chop it up and use a background image.  Instead a few lines of CSS3 can replace the need altogether for the image helping to improve the speed of your webpages!

Share


Related Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books