33

WebKit has introduced the ability to create CSS gradients. For example, with the following code:

-webkit-gradient(linear, left top, left bottom, from(#fff), to(#000));

However, is it possible to have an opacity gradient using CSS? I want the gradient to be a single color on one side, and fade to zero opacity on the other.

Cross-browser compatibility isn't important; I just need it to work in Google Chrome.

Is there some way to do this using CSS? If not, can something similar be done using JavaScript (not jQuery)?

Thanks for your help.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
木川 炎星
  • 3,893
  • 13
  • 42
  • 51

3 Answers3

23

Yes

for the colors, use rgba(x, y, z, o) where o is the opacity

should work

e.g.

background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 1)), to(rgba(0, 0, 0, 0)));

Edit: For the final value (opacity) 1 is opaque & 0 is transparent

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
Jasper
  • 493
  • 3
  • 9
16

Yup, rgba(red, green, blue, alpha) is what you should use http://www.w3.org/TR/css3-color/#rgba-color, example (Try it out on jsFiddle):

/* Webkit */
background: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(1, rgba(0,0,0,0.0)), /* Top */
    color-stop(0, rgba(0,0,0,1.0)) /* Bottom */
);

/* Gecko */
background: -moz-linear-gradient(
    center bottom,
    rgba(0,0,0,1.0) 0%, /* Bottom */
    rgba(0,0,0,0.0) 100% /* Top */
);
antonj
  • 21,236
  • 6
  • 30
  • 20
2

not tested, but this should work (in FF this works (with a different syntax) - i'm not sure if safari/webkit knows rgba):

-webkit-gradient(linear, left top, left bottom, from(rgba(255,255,255,1)), to(rgba(0,0,0,0)));
oezi
  • 51,017
  • 10
  • 98
  • 115
  • I might've misunderstood something, but why would you expect a `-webkit` vendor-prefixed property to work in Firefox? (`-webkit` applies to Chrome and Safari, and one or two others; `-moz` is for Firefox; `-o` is Opera; `-ms` is, apparently, IE...) – David Thomas Dec 19 '10 at 00:44
  • thanks for the hint, i've edited that... i just forgot to write some text (thats what happens if you drink alcohol while sufing on stackoverflow on sunday evening -.-') – oezi Dec 19 '10 at 02:12