Modern browsers (Firefox 3.6+, Safari 4+, all versions of Chrome, Opera and IE 10+) support gradients in CSS. The syntax for gradients has seen many iterations, improvements and variations since it was first proposed by Apple in 2008; this article focuses on the final unprefixed specification. Older browsers will require prefixed values and variations on the syntax, or an SVG solution; I suggest using one of the gradient generators at the end of this article to create the full range of values to support all browsers.
At its most basic, the syntax for a linear gradient is very simple:
body {
background-image: linear-gradient(#a00, black);
}
Linear gradients have just two required values: starting color and ending color. By default, the gradient direction is top-to-bottom, but may be specified as a keyword (top
, left
, bottom
, right
), a pair of keywords representing a corner (bottom right
, for example) or an angle. If keywords are used, they must be preceded by to
; angles are specified in the same way as CSS transforms, as bearing directions (i.e. 0deg
is north, or the 12 o'clock position, with angles growing to the right (clockwise)).
The color values may be specified in any method supported by CSS: keywords, hexadecimals, rgb, rgba, or hsl values.
While gradients are technically images, and should be applicable anywhere images are used on a web page, most browsers currently support the use of gradients only in backgrounds, so it is that use that I’ll show here.
body {
background-image: linear-gradient(45deg, #a00, black);
}
By default, colors are equally distributed along the gradient – in this case, red at the starting position (0%), black at the end (100%). If we add intermediary colors, they will be evenly distributed along this continium. If we want to add stops – for example, to have black start from the ⅓rd point, do the following:
body {
background-image: linear-gradient(#a00, black 33%);
}
You can add as many colors as you wish into this gradient, each with their own individual stops – in fact, you could copy them directly from PhotoShop’s gradient tool. As they are treated as just another image, it's entirely possible to combine gradients with background images, as shown in the Pop Art CSS3 Backgrounds article.
Note that gradients will automatically extend the complete height and width of the element, although the actual computed height of the element is often different from its perceived “visual” height. Visual misapplication of gradients is often due to not having the element sized correctly: this is especially true in the body
, which often needs a min-height: 100%
or min-height: 100vh
declaration in order to have the gradient extend fully to the bottom of the browser window.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.