Friday, September 14, 2012

CSS Gradient Background – Cross Browser!

CSS Gradient Background
You read that right. This works in:

  • Firefox >=3.6
  • MSIE >=5.5 (!)
  • Safari >=4
  • Chrome

And it degrades gracefully in older browsers and Opera.

It was orignally developed by FakeDarren, who posted a great little CSS button example. I find it useful for those times when designers get all fancy with gradiented backgrounds.

I've condensed Darren’s CSS down to these four lines plus comments, which will give you the lovely Green-to-Black CSS gradient background.

/* thanks to http://blog.fakedarren.com/2010/01/cross-browser-css-gradients/ */
/* and http://www.puremango.co.uk/2010/04/css-gradient/ */

.gradientV{
    /* fallback (Opera) */
    background: #008800;
    /* Mozilla: */
    background: -moz-linear-gradient(top, #00FF00, #000000);
    /* Chrome, Safari:*/
    background: -webkit-gradient(linear, left top, left bottom, from(#00FF00), to(#000000));
    /* MSIE */
    filter: progid:DXImageTransform.Microsoft.Gradient(StartColorStr='#00FF00', EndColorStr='#000000', GradientType=0);
}

And as you may have guessed by the ‘V’ in the class name, you can also do horizontal gradients – here are some more examples for left-right gradients, and we see what happens when we apply animations to a gradiented DIV.

Horizontal Gradient CSS

/* thanks to http://blog.fakedarren.com/2010/01/cross-browser-css-gradients/ */
/* and http://www.puremango.co.uk/2010/04/css-gradient/ */

.gradientH{
    /* fallback (Opera) */
    background: #008800;
    /* Mozilla: */
    background: -moz-linear-gradient(left, #00FF00, #000000);
    /* Chrome, Safari:*/
    background: -webkit-gradient(linear, left top, right top, from(#00FF00), to(#000000));
    /* MSIE */
    filter: progid:DXImageTransform.Microsoft.Gradient( StartColorStr='#00FF00', EndColorStr='#000000', GradientType=1);
}

So now we no longer need little 1px slices in the background-image property, just remember to make sure all the colors in each line of CSS match up, and that you choose a nice flat colour fallback that works with your content.

I'm very impressed with how slim the CSS needs to be to get this great image-free cross-browser CSS background gradient. Just saying those words gives me shivers. Yay for CSS!

One other thing that this allows, which was never possible using css background images, is stretchable gradients. Not only can the content be allowed to expand ‘naturally’ via site updates etc, but we can actually animate gradiented DIVs and preserve the effect!