Greyscale Background Css Images

后端 未结 5 2152
独厮守ぢ
独厮守ぢ 2020-11-27 14:42

I\'ve searched a lot on the web but I cannot find a cross browser solution to fade a css backgrund image to greyscale and back.

The only working solution is to apply

5条回答
  •  情深已故
    2020-11-27 15:31

    I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.

    You can use background-blend-mode property to achieve a greyscale image:

    #something {
      background-color: #fff;
      background-image: url("yourimage");
      background-blend-mode: luminosity;
    }
    

    If you want to remove the effect, just change the blend-mode to initial.

    You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something.

    You can also use two images, one with color and the other without and set both as background and play with other blend modes.

    https://www.w3schools.com/cssref/pr_background-blend-mode.asp

    It won't work on Edge though.

    EDIT: I've miss the "fade" part of the question.

    If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:

    #something {
      background-color: rgba(255,255,255,1);
      background-image: url("yourimage");
      background-blend-mode: luminosity;
      transition: background-color 1s ease-out;
    }
    #something:hover {
      background-color: rgba(255,255,255,0);
    }
    

    I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ

提交回复
热议问题