Overlay a CSS gradient with an RGBA colour?

I’m wanting to add a transparent black overlay to a button for it’ :active state, so when you click it, it’s the same gradient but with just an overlay of e.g. rgba(0,0,0,.3)

The way I thought this would work is (using webkit in this example):

background:rgba(0,0,0,.3), -webkit-linear-gradient(top, #fcfcfc 0%,#bababa 100%);

or without the comma, and the order reversed… but nothing shows up at all!

I’m not keen on adding another div to act as the overlay to do it, so is there a strictly CSS way to do this? I was thinking maybe it’s a :before
or :after
pseudo class, but I don’t have a clue how to use these!

Would really appreciate an answer, this has been bugging me for a long time.

Problem courtesy of: alexbass

Solution

You can do it with ::after
pseudo-element.

First, you need to define the button CSS with position: relative
and then use ::after
with position: absolute
, like this:

.button {
  position: relative;
}

.button:active::after {
    content: ' ';
    position: absolute;
    background: rgba(0, 0, 0, 0.3);
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}


Live Fiddle demo

Solution courtesy of: Fong-Wan Chau

Discussion

Think in Reverse

Set background-color: black
and overlay the gradient with your colors converted from hex to rgba (initially set to 1
for alpha), then on :active
fade the gradient to 0.7
(which will show 30% black) alpha.

See the fiddle
.

button {
    background-color: black;
    background-image: -webkit-linear-gradient(top, rgba(252, 252, 252, 1) 0%, rgba(186, 186, 186, 1) 100%);
    background-image: -moz-linear-gradient(top, rgba(252, 252, 252, 1) 0%, rgba(186, 186, 186, 1) 100%);
}

button:active {
    background-image: -webkit-linear-gradient(top, rgba(252, 252, 252, .7) 0%, rgba(186, 186, 186, .7) 100%);
    background-image: -moz-linear-gradient(top, rgba(252, 252, 252, .7) 0%, rgba(186, 186, 186, .7) 100%);    
}

Discussion courtesy of: ScottS

You can’t do that; rgba
defines a colour, not an image. What you can do is use a gradient that’s not a gradient:

background: -webkit-linear-gradient(rgba(0, 0, 0, .3), rgba(0, 0, 0, .3)), -webkit-linear-gradient(top, #fcfcfc 0%,#bababa 100%);

This is why I always specify background-image
instead of using the shorthand when developing – it makes debugging easier.

Discussion courtesy of: Ryan

This recipe can be found in it’s original form on Stack Over Flow
.

稿源:CSS3 Recipes (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Overlay a CSS gradient with an RGBA colour?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录