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

Fireflight picture Fireflight · Aug 5, 2011 · Viewed 51k times · Source

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

Answer

BoltClock picture BoltClock · Aug 5, 2011

This is now possible with custom properties:

.brown { --rgb: 118, 76, 41; }
.green { --rgb: 51, 91, 11; }

a { display: block; position: relative; }
div { position: absolute; bottom: 0; background-color: rgba(var(--rgb), 0.8); }
a:hover div { background-color: rgba(var(--rgb), 1); }

To understand how this works, see How do I apply opacity to a CSS color variable?

If custom properties are not an option, see the original answer below.


Unfortunately, no, you'll have to specify the red, green and blue values again for each individual class:

a { display: block; position: relative; }

.brown { position: absolute; bottom: 0; background-color: rgba(118, 76, 41, 0.8); }
a:hover .brown { background-color: rgba(118, 76, 41, 1); }

.green { position: absolute; bottom: 0; background-color: rgba(51, 91, 11, 0.8); }
a:hover .green { background-color: rgba(51, 91, 11, 1); }

You can only use the inherit keyword alone as a value for the property, and even then the use of inherit isn't appropriate here.