CSS Gradients

Course- Javascript >

CSS3 gradients allow you to generate smooth transitions between two or more specified colors, where previously you had to employ images to achieve these effects. With CSS3 gradients you can reduce the download time, cache memory, and bandwidth usage that these images would have cost. CSS3 gradients perform better when zoomed, too.

CSS3 offers two types of gradient: Linear Gradients, directed down/up/left/right/diagonally, and Radial Gradients, directed outwards from a defined center.

Linear Gradients

To create a linear gradient in CSS3, you must define at least two colors to serve as the end points of the gradient. You can also define a starting point and a direction (that is, top to bottom, left to right, or an angle) for the gradient effect.

#div1 {
width: 600px;
height: 350px;
background: -webkit-linear-gradient(red, #6699cc);
background: -o-linear-gradient(red, #6699cc);
background: -moz-linear-gradient(red, #6699cc);
background: linear-gradient(red, #6699cc);
}                 
                 

Here I’ve mixed the ways the colors are defined, using both color names (here red) and #rrggbb notation. I haven’t specified a direction for the gradient, so the default top-tobottom will be used by the browser

A CSS3 linear gradient

You can also enter a direction for the gradient; for instance, suppose you want the gradient to be directed left-to-right instead of top-to-bottom, like so:

background: linear-gradient(to right, red , #6699cc);

The following line defines a diagonal gradient:

background: linear-gradient(to bottom right, red , #6699cc);

If you want total control over the direction of the gradient, define an angle:

background: linear-gradient(135deg, red, #6699cc);

Radial Gradients

A radial gradient is defined by its center and (like its linear counterpart) must have at least two colors defined to act as end points for the gradient effect:

background: radial-gradient(red, #6699cc);

A radial gradient specified this way displays as shown below snapshot

A CSS3 radial gradient

You can also set a location parameter for the center of the radial gradient, using the at keyword:

background: radial-gradient(at top left, red, #6699cc); Moving the center of the radial gradient