CSS gradients tutorial

CSS gradients allow web developers to specify fading and transitional colors on their elements. Unfortunately, not all browsers support CSS gradients and those that support them use different syntaxes. In this post I'm going to show you how to use CSS gradients by tackling browser discrepancies.

Safari and Chrome

Safari and Chrome use this syntax:

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

which means the following:

  • type: the type of gradient (e.g. linear)
  • point: the x and y coordinates where the gradient should start (e.g. 0 0 or keywords)
  • point: the x and y coordinates where the gradient ends (e.g. 0 100% or keywords)
  • stop: the start (from()) and end (to()) colors.

An example:

#test {
	background: -webkit-gradient(linear, left top, left bottom, from(#f90), to(#c40));
}

Firefox

Firefox uses this syntax:

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

which means the following:

  • point/angle: where the gradient starts (also angle length are accepted)
  • stop: the start color
  • stop: the end color.

An example:

#test {
	background: -moz-linear-gradient(top,  #f90,  #c40);

}

Internet Explorer

IE supports gradients through its filter syntax:

filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='value', endColorstr='value');

which means the following:

  • startColorstr: start color with six hexadecimal digits
  • endColorstr: end color with six hexadecimal digits.

An example:

#test {

  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff9900', endColorstr='#cc4400');

}

Putting all together

To make sure that non supporting browsers will always get a background color, you should use the following approach:

#test {

	background: #f90;
	filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff9900', endColorstr='#cc4400');
	background: -webkit-gradient(linear, left top, left bottom, from(#f90), to(#c40));
	background: -moz-linear-gradient(top,  #f90,  #c40);

	width: 100%;
	height: 100px;

}

First, you specify a fallback background color and then you use gradients. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.