How to make a simple gradient using box-shadow CSS property

This article demonstrates that box-shadow CSS property can be used not only to create shadows around an element, but also to create a gradient inside an element as background.
Actually, the sole purpose of this property is to create shadows. But, it can contain inset keyword in its value which positions a shadow inside of the element instead of the outside of the element. Using an inner shadow we can make an illusion of gradient. Such approach is perfect solution for simple gradients. Of course there are CSS3 gradients which can create very complex gradients, but box-shadow CSS property is easier in use than CSS3 gradients which have complex syntax. Also box-shadow property has more browser support than CSS3 gradient properties.
Here is syntax of box-shadow property:
box-shadow: h-shadow v-shadow blur spread color inset;
h-shadow
- position of horizontal shadow;v-shadow
- position of vertical shadow;blur
- blur distance;spread
- size of shadow;color
- color of shadow;inset
- changes shadow from an outer shadow to an inner shadow.
All examples below are applied to div element which has a fixed width and height. Here are styles for this:
div { width: 300px; height: 150px; }
The following CSS styles change color of the background from blue to yellow vertically:
div { background-color: yellow; -webkit-box-shadow: 0 150px 40px -75px blue inset; box-shadow: 0 150px 40px -75px blue inset; }
In the styles above only two things should be taken into the consideration:
- Colors of gradient. The top color can be changed in box-shadow CSS property (fifth value), and the bottom color in background-color CSS property.
- Level of transition between colors. This level can be changed by third value in box-shadow CSS property.
Let's change the level of transition from 40 pixels to 120 pixels using the following CSS styles:
div { background-color: yellow; -webkit-box-shadow: 0 150px 120px -75px blue inset; box-shadow: 0 150px 120px -75px blue inset; }
Let's change the colors of gradient from blue and yellow to green and orange using the following CSS styles:
div { background-color: orange; -webkit-box-shadow: 0 150px 120px -75px green inset; box-shadow: 0 150px 120px -75px green inset; }