Search code examples
cssbuttontextbackgroundgrayscale

Grayscale only button background but not text


I have several buttons with different background images. I would like to achieve to have a grayscale filter on them by default and on hover remove the grayscale filter.

I have this already but the problem is that the text of the buttons are also grayed out which i would like to avoid. I Couldn't figure out how to apply grayscale filter only on button backgrounds but not on text.

Now I have a main css class for the buttons

.box {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
position:relative;
color: red;
cursor:pointer;
text-align: center;
width: 160px;
height: 160px;
}
.box:hover {
-webkit-filter: grayscale(0%);
filter: grayscale(0%);
color: blue;
}

and I apply the backgrounds for each button in html code

<button onclick="buttonFunction()" button class="button box" style="background: url(background1.jpg); background-size: 100%;" >Gray button text:( </button>

Any idea how to add grayscale filter only button backgrounds and keep the button texts colored?

Thanks


Solution

  • Applying the filter property to an element will affect the children of that element. You will not be able to unset / reset the filter property for the children.

    If you don't want to / can't use the pseudoelement approach in the other answers, then you could change your HTML to create the effect you want.

    Add the image as an img element in the button, and place the text in a span. You can then apply the filter to the img.

    .box {
      cursor: pointer;
      width: 160px;
      height: 160px;
      position: relative;
      padding: 0;
      display: inline-flex;
      justify-content: center;
      align-items: center;
    }
    
    .box img {
      -webkit-filter: grayscale(100%);
      filter: grayscale(100%);
      position: absolute;
      max-width: 100%;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
    }
    
    .box:hover img {
      -webkit-filter: grayscale(0%);
      filter: grayscale(0%);
    }
    
    .text {
      color: red;
      z-index: 1;
    }
    
    .box:hover .text {
      color: blue;
    }
    <button onclick="buttonFunction()" button class="button box"><img src="https://unsplash.it/200x200"><span class="text">Gray button text:(</span></button>