CSS: Emulate linear gradients with inset box shadows

Updated . Posted . Visible to the public.

Why is this useful?

  • You can have a background image on the same element, overlaying it with a transparent gradient.
  • Since you are probably using gradients to give an element a glossy or three-dimensional feel, box shadows work much better for this. This is because linear gradients always stretch to the full size of the element (which can grow with user input), while a natural shine or shadow only highlights a fixed size on the top or bottom.
  • Browser support for linear gradients is a mess. I avoid using them. In particular, IE 7-9 can only emulate gradients with a weirdo DirectX filter directive which has issues.

Examples

Take this gradient from top to bottom:

background-image: linear-gradient(top, red 0%, bottom 100%);

You can emulate this with a box shadow (assuming that the element is 50px high):

background-color: blue
box-shadow: 0 50px 50px -50px red

Compatibility

Real browsers and IE9+ Show archive.org snapshot .

Henning Koch
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2012-10-19 12:09)