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:
- Direction can be:
- to top
- to right
- to bottom
- to left
- 30deg (30 degree clockwise angle from upwards direction)
- We can define multiple stops
- 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:
- shape can be circle or ellipse. (Unless size is single lenght, it default to ellipse if omitted)
- We can define multiple stops
- position default to center.
- size can be implicit ( closest-side, farthest-side, closest-corner, farthest-corner). farthest-corner is default.
- 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
Specification | Status | Categories |
---|---|---|
CSS Gradients | W3C Candidate Recommendation | CSS3 |
Chrome | Firefox | IE | Edge | Safari | Opera |
---|---|---|---|---|---|
Yes 26+ | Yes 16+ | Yes 10+ | Yes 12+ | Yes 6.1+ | Yes 12.1+ |
Android Chrome | Android Firefox | iOS Safari | IE Mobile | Opera Mobile |
---|---|---|---|---|
Yes 47+ | Yes 44+ | Yes 7.0-7.1+ | Yes 10+ | Yes 12.1+ |
source: caniuse.com