alexbass
alexbass

Reputation: 53

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.

Upvotes: 5

Views: 3923

Answers (3)

Fong-Wan Chau
Fong-Wan Chau

Reputation: 2289

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

Upvotes: 2

Ry-
Ry-

Reputation: 224921

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.

Upvotes: 3

ScottS
ScottS

Reputation: 72261

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

Upvotes: 1

Related Questions