Gradients with CSS

Not so long ago you had to use images if you wanted to display gradients. But with CSS 3 that isn't absolutely necessary anymore. Exceptionally the Internet Explorer by Microsoft was the first browser that ever supported gradients using filters. It wasn't CSS conform, but hey, it worked anyway.

Today browser support isn't that good - almost every browser still needs vendor prefixes so that you have to write a lot of code to get your gradient displayed. Apart from Internet Explorer 6 that was able to display gradients from version 6 not all older browser displays gradients - Opera, Firefox, Safari don't display gradients if it's not the latest version. Chrome displays gradients since this browser isn't that old but it still isn't that stable.

To show how it works we're creating a simple linear gradient from top to bottom from ffee68 nach f0cd09. We will create a div box that uses the gradient as background. First of all we define a fallback background for older browsers. That's the code:

CSS
/* Fallback for old browsers: */background: #f0cd09;/* official W3C syntax: */background: linear-gradient(top, #ffee68 0%,#f0cd09 100%);/* Mozilla syntax, from Firefox 3.6: */background: -moz-linear-gradient(top, #ffee68 0%, #f0cd09 100%);/* old Webkit syntax, Safari from version 4 and old Chrome versions */background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffee68), color-stop(100%,#f0cd09));/* new Webkit syntax, Safari from version 5.1, Chrome from version 10 */background: -webkit-linear-gradient(top, #ffee68 0%,#f0cd09 100%); /* syntax for Opera, from version 11.10: */background: -o-linear-gradient(top, #ffee68 0%,#f0cd09 100%);/* Microsoft syntax, from Internet Explorer 10 */background: -ms-linear-gradient(top, #ffee68 0%,#f0cd09 100%); /* and syntax for Internet Explorer 6 bis 9 */filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffee68', endColorstr='#f0cd09',GradientType=0 );

As you can see the current browser versions are geared to the syntax by W3C, they only need the vendor prefix, e.g. -moz oder -webkit.

If you need to support all Webkit versions you'll have to write the new as well as the old syntax. Same goes for Internet Explorer. Let's have a look at our div box.

And here is the code I've used for the box

divBoxPreview.png

Update 2016:

[pp]Time passed by and things got better. You have to write less code today since browser support is much better. Relevant is from todays view the W3C syntax and the new webkit syntax so older Android browsers can display the gradients, since they're still in use. So that's how the code looks today:

CSS
background-color: #f0cd09;/* Webkit syntax, Safari from version 5.1 - Version 6.1, Chrome from version 10 - version 26, Android Browser version 4.0 - version 4.3*/background-image: -webkit-linear-gradient(top, #ffee68 0%,#f0cd09 100%); /* W3C syntax: */background-image: linear-gradient(top, #ffee68 0%,#f0cd09 100%);