CSS gradients

June 6th, 2010 by JorisO | Filed under CSS3, Faster websites, Front-end development.

CSS gradients promise a great leap forward for the graphical capabilities of CSS. A CSS gradient is in fact a browser-generated image, consisting of smooth fades between several colors. Letting CSS create these will decrease download times and allows for many new interesting DHTML possibilities.

Both linear and radial gradients are supported by the new CSS specifications. At the time of writing CSS gradients are supported by Mozilla and Webkit browsers but Internet explorer offers something similar in it’s usual non-compliant manner.

The syntax with which CSS gradients are implemented by different engines currently differs quite a bit at first view. But the underlying principles for specifying gradients are similar and close to current W3C specifications for this new functionality.

Chrome / Safari

Webkit was the first to introduce them. The syntax for creating css gradients in Webkit browsers (Chrome, Safari) is:

-webkit-gradient(
<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)

The Webkit gradient syntax is described here:

http://webkit.org/blog/175/introducing-css-gradients/

Firefox

Mozilla Firefox and it’s siblings support this feature since version 3.6
The syntax in this browser is as follows:

-moz-linear-gradient(
 [<point> || <angle>,]? <stop>, <stop> [, <stop>]* )

The Mozilla gradient syntax is described here:

https://developer.mozilla.org/en/CSS/-moz-linear-gradient

Quick css gradient example ( that doesn’t work on IE )

.gradient{
  background: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0.16, rgb(234,27,204)),
    color-stop(0.58, rgb(255,54,245))
  );
background: -moz-linear-gradient(
    center bottom,
    rgb(234,27,204) 16%,
    rgb(255,54,245) 58%
  );
width:400px;
height:200px

}

Internet Explorer

Support it we must. Internet Explorer 8’s CSS gradients are implemented as a IE version specific filter which to keep things interesting is different from the specifications for IE 6 and 7 and doesn’t support stops.

To declare a gradient that looks the same on all browsers including Internet Explorer use something like the following:

#gradient {
	background-image: -moz-linear-gradient(top, #81a8cb, #4477a1); /* Firefox 3.6 */
	background-image: -webkit-gradient(linear,left bottom,left top,color-stop(0, #4477a1),color-stop(1, #81a8cb)); /* Safari & Chrome */
	filter:  progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1'); /* IE6 & IE7 */
	-ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#81a8cb', endColorstr='#4477a1')"; /* IE8 */
}

(source: Smashing Magazine)

Glrzad.com offers a very handy CSS gradient generator: http://gradients.glrzad.com which however ignores IE syntax completely.

Tags: , , , ,


Leave a Reply