木川 炎星
木川 炎星

Reputation: 4093

Can you create gradients that fade to opacity using CSS or JavaScript?

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.

Upvotes: 35

Views: 44541

Answers (3)

Jasper
Jasper

Reputation: 503

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

Upvotes: 24

oezi
oezi

Reputation: 51807

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)));

Upvotes: 2

antonj
antonj

Reputation: 21816

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 */
);

Upvotes: 16

Related Questions