Convert an image to grayscale in HTML/CSS

前端 未结 25 1824
青春惊慌失措
青春惊慌失措 2020-11-22 10:22

Is there a simple way to display a color bitmap in grayscale with just HTML/CSS?

It doesn\'t need to be IE-compatible (and I imagine it won\'t be) -- if

25条回答
  •  日久生厌
    2020-11-22 10:58

    Here's a mixin for LESS that will let you choose any opacity. Fill in the variables yourself for plain CSS at different percentages.

    Neat hint here, it uses the saturate type for the matrix so you don't need to do anything fancy to change the percentage.

    .saturate(@value:0) {
        @percent: percentage(@value);
    
        filter: url("data:image/svg+xml;utf8,#grayscale"); /* Firefox 3.5+ */
        filter: grayscale(@percent); /* Current draft standard */
        -webkit-filter: grayscale(@percent); /* New WebKit */
        -moz-filter: grayscale(@percent);
        -ms-filter: grayscale(@percent);
        -o-filter: grayscale(@percent);
    }
    

    Then use it:

    img.desaturate {
        transition: all 0.2s linear;
        .saturate(0);
        &:hover {
            .saturate(1);
        }
    }
    

提交回复
热议问题