I have the following CSS for a button:
.Button {
background-color: #somehex;
}
When the user hovers over the button, I want the background-color
to be a little darker. I have tried changing opacity, which didn't work, and currently am doing it this way:
.Button:hover {
transition: 0.2s ease-in;
background-color: #ALittleDarkerHex;
}
While this process works, it is really tedious because I have to manually look for a darker version of the color I am working with. I was wondering if there was an easier way to darken the background-color
of a button using CSS.
Add a dark layer on the top of it using background-image
. This method keeps your text visible in the same color while changing only the background.
.button {
display: inline-block;
color: #fff;
padding: 10px 20px;
font-size: 20px;
background-color: red;
}
.button:hover {
background-image: linear-gradient(rgb(0 0 0/40%) 0 0);
}
<div class="button"> some text </div>
<div class="button" style="background-color:lightblue;"> some text </div>
<div class="button" style="background-color:green;"> some text </div>
<div class="button" style="background-color:grey;"> some text </div>
To have a transition:
.button {
display: inline-block;
color: #fff;
padding: 10px 20px;
font-size: 20px;
background: linear-gradient(#0000, rgb(0 0 0/40%)) top/100% 800%;
background-color: red;
transition: 0.5s;
}
.button:hover {
background-position: bottom;
}
<div class="button"> some text </div>
<div class="button" style="background-color:lightblue;"> some text </div>
<div class="button" style="background-color:green;"> some text </div>
<div class="button" style="background-color:grey;"> some text </div>
Another idea with mix-blend-mode:
.button {
display: inline-block;
color: #fff;
padding: 10px 20px;
font-size: 20px;
background-color: red;
background-image: linear-gradient(rgb(0 0 0/40%) 0 0);
background-blend-mode: lighten;
}
.button:hover {
background-blend-mode: darken;
}
<div class="button"> some text </div>
<div class="button" style="background-color:lightblue;"> some text </div>
<div class="button" style="background-color:green;"> some text </div>
<div class="button" style="background-color:grey;"> some text </div>
You can also consider a big inset box-shadow and you will also have the ability to add transition:
.button {
display: inline-block;
color: #fff;
padding: 10px 20px;
font-size: 20px;
background-color: red;
box-shadow: 0 0 0 100vmax inset rgb(0 0 0/var(--o,0%));
transition: .4s;
}
.button:hover {
--o: 40%;
}
<div class="button"> some text </div>
<div class="button" style="background-color:lightblue;"> some text </div>
<div class="button" style="background-color:green;"> some text </div>
<div class="button" style="background-color:grey;"> some text </div>