23

I'm randomly generating colors into boxes of 50x50px and when I hover them I want them to become darker, but remain the same color.

I've tried setting li:hover to a dark color with transparency

background-color: rgba(91, 91, 91, 0.51) !important;

but it doesn't look good, it's making the whole <li> (which is the box I'm referring to) transparent on hover.

How do I achieve this?

Here is a Plunker.

simeg
  • 1,889
  • 2
  • 26
  • 34

1 Answers1

30

Sorry, it's not possible to only change the alpha. You have to specify the red, green and blue values for each individual class.

But there's another way which is answered here and I'll copy below: https://stackoverflow.com/a/16910152/1026017

Here's a demo: http://codepen.io/chrisboon27/pen/ACdka

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 (variation on the gif method - may have performance issue):

.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;
}
Community
  • 1
  • 1
Scott
  • 3,736
  • 2
  • 26
  • 44
  • 2
    Darn, you beat me by a few seconds! :P – Terry Jan 10 '15 at 16:21
  • 1
    Method three worked, thanks pal – Sergio Jan 31 '17 at 20:33
  • 5
    Good answer, thanks. I found it useful and simpler to reverse this method: don't use anything additional without hover, and on hover use: box-shadow: inset 0 0 0 99999px rgba(128,128,128,0.2). This was necessary for me because my rows alternate white and light gray, so the original answer didn't change the white. – Dovev Hefetz Apr 20 '17 at 12:05
  • Now it *is* possible to change `alpha` only. See e.g. https://stackoverflow.com/a/45463603 – djvg Sep 03 '21 at 08:43