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

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.


No, it's not possible.

You could try a CSS pre-processor, though, if you want to do this sort of thing.

From what I could see, at least LESS and Sass have functions that can make colors more, or less, transparent.


You could do various things to avoid having to hard code the numbers if you want to. Some of these methods only work if you use a plain white background as they're really adding white on top rather than reducing opacity. The first one should work fine for everything provided:

  • you aren't already using the psuedo-element for something; and
  • you can set position to relative or absolute on the <div> tag

Option 1: ::before psuedo-element:

.before_method{
  position:relative;
}
.before_method:before{
  display:block;
  content:" ";
  position:absolute;
  z-index:-1;
  background:rgb(18, 176, 41);
  top:0;
  left:0;
  right:0;
  bottom:0;
  opacity:0.5;
}
.before_method:hover:before{
  opacity:1;
}

Option 2: white gif overlay:

.image_method{
  background-color: rgb(118, 76, 41);
  background-image: url(https://upload.wikimedia.org/wikipedia/commons/f/fc/Translucent_50_percent_white.png)
}
.image_method:hover{
  background-image:none;
}

Option 3: box-shadow method:

A variation of the gif method, but may have performance issues.

.shadow_method{
  background-color: rgb(18, 176, 41);
  box-shadow:inset 0 0 0 99999px rgba(255,255,255,0.2);
}
.shadow_method:hover{
  box-shadow:none;
}

CodePen examples: http://codepen.io/chrisboon27/pen/ACdka