1

I would like to add a darkened background color to my buttons when someone hovers over them. My problem is that the buttons have a background-color: transparent by default (when not being hovered over).

So that means the buttons have different background colors (depending on the background div's color). Therefore I cannot make 20+ css classes for every darkened color. I would like a solution that I can just add to my single icon-button class. See my examples for a better explanation.

I would like something like this:

.icon-button:hover {
    background-color: black;
    background-color-opacity: 25%;
}

Instead of doing this:

.icon-button.white:hover {
    background-color: #xxxxxx; (darkened white)
}

.icon-button.red:hover {
    background-color: #xxxxxx; (darkened red)
}

.icon-button.purple:hover {
    background-color: #xxxxxx; (darkened purple)
}

.icon-button.green:hover {
    background-color: #xxxxxx; (darkened green)
}

.....

(For some reason my image upload is failing, check it here) https://i.stack.imgur.com/jn9MR.jpg

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Paul Kruger
  • 2,094
  • 7
  • 22
  • 49

1 Answers1

2

You could use an rgba colour for the background. rgba has an alpha channel that dictates the opacity of the colour layer. This would be the equivalent of the background-color-opacity that you mention.

div {
  padding: 15px;
  text-align: center;
}
div:nth-child(1) {
  background: red;
}

div:nth-child(2) {
  background: green;
}

div:nth-child(3) {
  background: blue;
}

button {
  background: transparent;
  border: 1px solid white;
  color: white;
  padding: 15px 30px;
  transition: all .2s ease;
}

button:hover {
  background: rgba(0,0,0,0.3);
}
<div>
  <button type="button">
    Button
  </button>
</div>

<div>
  <button type="button">
    Button
  </button>
</div>

<div>
  <button type="button">
    Button
  </button>
</div>
Turnip
  • 35,836
  • 15
  • 89
  • 111
  • My dear friend, this is an AMAZING answer. Thank you very much :) – Paul Kruger Aug 07 '18 at 13:14
  • why you reopened the post? it was a perfect duplicate of this : https://stackoverflow.com/questions/48847205/change-background-color-opacity-without-changing-background-image-opacity – Temani Afif Aug 07 '18 at 13:18
  • @TemaniAfif I don't believe it is a dupe of that question. This is about overlaying a darkened colour over a parent elements background colour. The dupe is about changing the background colour of the element itself. – Turnip Aug 07 '18 at 13:21
  • Sorry but they are exactly the same for me ... even your answer is similar to one there (https://stackoverflow.com/a/48847757/8620333). wording are different but the visual result is the same – Temani Afif Aug 07 '18 at 13:34
  • Close it if you want. It's no skin off my nose. – Turnip Aug 07 '18 at 13:35
  • we cannot close twice ;) – Temani Afif Aug 07 '18 at 13:44