Is it possible to change only the alpha of a rgba background colour on hover?

Viewed 67987

I have a set of <a> tags with differing rgba background colours but the same alpha. Is it possible to write a single css style that will change only the opacity of the rgba attribute?

A quick example of the code:

 <a href="#"><img src="" /><div class="brown">Link 1</div></a>
 <a href="#"><img src="" /><div class="green">Link 2</div></a> 

And the styles

a {display: block; position: relative}
.brown {position: absolute; bottom: 0; background-color: rgba(118,76,41,.8);}
.green {position: absolute; bottom: 0; background-color: rgba(51,91,11,.8);}

What I would like to do is write a single style that would change the opacity when the <a> is hovered over, yet keep the colour unchanged.

Something like

a:hover .green, a:hover .brown {background-color: rgba(inherit,inherit,inherit,1);}
15 Answers

Simple workaround with opacity if you can accommodate a slight change in background-color:

.yourClass {
    // Your style here //
    opacity: 0.9;
}

.yourClass:hover, .yourClass:focus {
    opacity: 0.7;
}

.yourClass:active {
    opacity: 1;
    box-shadow: none;
}

.yourClass:hover, .yourClass:focus, .yourClass:active {
    text-decoration: none;
    outline: none;
}

Building on Yu Zhang's answer:

In :root, (or parent component in Blazor) set css variables:

--bg-img-light: linear-gradient(hsla(255,100%,100%,.2) 100%, transparent 100%);
--bg-img-dark: linear-gradient(hsla(0,0%,0%,.2) 100%, transparent 100%);

Then on any element that you want to apply a hover effect on:

.buttontomakelighter:hover {
  background-image: var(--bg-img-light);
}

.buttontomakedarker:hover {
  background-image: var(--bg-img-dark);
}
Related