CSS3 Gradient examples

A gradient is an image that smoothly fades from one color to another. These are commonly used for subtle shading in background images, buttons, and many other things. We can have linear and radial gradients (optionally repeating). It applies to background-image property (or shorthand background).

Linear gradient

Syntax:

background-image: linear-gradient(direction, color-stop1, color-stop2, ...);
background-image: repeating-linear-gradient(direction, color-stop1, color-stop2, ...);

Few points to note:

  1. Direction can be:
    1. to top
    2. to right
    3. to bottom
    4. to left
    5. 30deg (30 degree clockwise angle from upwards direction)
  2. We can define multiple stops
  3. Color stops can optionally have position markers (10px, 20%, etc.)

Examples:

In the following code, CSS property background-image can be changed to the following values
  • linear-gradient(yellow, blue)
  • linear-gradient(to right, yellow, blue)
  • linear-gradient(to right, yellow, blue 20%)
  • linear-gradient(45deg, yellow, blue)
  • repeating-linear-gradient(yellow, blue 20px)
<style type="text/css" media="screen">
.gradientbox {
  width: 200px; height: 100px;
  background-image: linear-gradient(yellow, blue);
}
</style>

<div class="gradientbox"></div>
background-image refresh

Radial gradient

background-image: radial-gradient(size shape at position, stop1, stop2, ...)
background-image: repeating-radial-gradient(size shape at position, stop1, stop2, ...)

Few points to note:

  1. shape can be circle or ellipse. (Unless size is single lenght, it default to ellipse if omitted)
  2. We can define multiple stops
  3. position default to center.
  4. size can be implicit ( closest-side, farthest-side, closest-corner, farthest-corner). farthest-corner is default.
  5. size can also be explicit. One value for circle and two values for ellipse.

Examples:

In the following code, CSS property background-image can be changed to the following values
  • radial-gradient(yellow, blue)
  • radial-gradient(circle, yellow, blue)
  • radial-gradient(5em circle, yellow, blue)
  • radial-gradient(circle at top left, yellow, blue)
  • radial-gradient(yellow, blue, green, red)
  • repeating-radial-gradient(1em circle, yellow, blue)
<style type="text/css" media="screen">
.gradientbox {
  width: 200px; height: 100px;
  background-image: radial-gradient(yellow, blue);
}
</style>

<div class="gradientbox"></div>
background-image refresh

Specification and Browser compatibility

SpecificationStatusCategories
CSS GradientsW3C Candidate RecommendationCSS3
Desktop
ChromeFirefoxIEEdgeSafariOpera
Yes 26+ Yes 16+ Yes 10+ Yes 12+ Yes 6.1+ Yes 12.1+
Mobile
Android ChromeAndroid FirefoxiOS SafariIE MobileOpera Mobile
Yes 47+ Yes 44+ Yes 7.0-7.1+ Yes 10+ Yes 12.1+
source: caniuse.com
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments