Convert an image to grayscale in HTML/CSS

前端 未结 25 1528
青春惊慌失措
青春惊慌失措 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:50

    Following on from brillout.com's answer, and also Roman Nurik's answer, and relaxing somewhat the the 'no SVG' requirement, you can desaturate images in Firefox using only a single SVG file and some CSS.

    Your SVG file will look like this:

    
    
        
            
        
    
    

    Save that as resources.svg, it can be reused from now on for any image you want to change to greyscale.

    In your CSS you reference the filter using the Firefox specific filter property:

    .target {
        filter: url(resources.svg#desaturate);
    }
    

    Add the MS proprietary ones too if you feel like it, apply that class to any image you want to convert to greyscale (works in Firefox >3.5, IE8).

    edit: Here's a nice blog post which describes using the new CSS3 filter property in SalmanPK's answer in concert with the SVG approach described here. Using that approach you'd end up with something like:

    img.desaturate{
        filter: gray; /* IE */
        -webkit-filter: grayscale(1); /* Old WebKit */
        -webkit-filter: grayscale(100%); /* New WebKit */
        filter: url(resources.svg#desaturate); /* older Firefox */
        filter: grayscale(100%); /* Current draft standard */
    }
    

    Further browser support info here.

提交回复
热议问题