Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't CSS filters work on SVG elements in Chrome?

Tags:

css

svg

As far as I understand, CSS filters should work anywhere in Chrome, but I fail to make them apply to SVG elements.

This works fine in all most browsers:

div{ filter:sepia(50%) }

However, this will not work in Chrome:

rect{ filter:sepia(50%) }

Here is an example:

div{
    width:100px;
    height:50px;
    background-color:red;
}
rect{
    fill:red;
}
rect:hover, div:hover{
    -webkit-filter:sepia(50%);
    -moz-filter:sepia(50%);
    filter:sepia(50%);
}
<h2>SVG</h2>
<svg width="100" height="50">
    <rect x="0" y="0" width="100" height="50"/>
</svg>


<h2>DIV</h2>
<div></div> 

...and here is a fiddle: https://jsfiddle.net/LtffLagn/2/

like image 385
leo Avatar asked Sep 14 '15 14:09

leo


People also ask

How to apply filter to SVG?

To use an SVG filter in CSS, use the url keyword, define a URI that defines an SVG file, and reference a filter with an id . That's it! The waves filter you see above is a modified version of the presets included at yoksel.github.io/svg-filters/. The waves effect shows the power of SVG filters.


1 Answers

All credit to @Robert Longson, who gave the answer: CSS filters can not be applied to SVG elements in Chrome. They can, however, be re-implemented as SVG filters, with some extra work. This is what I ended up with:

rect{
  fill:red;
}
rect:hover{
    filter:url("#sepia");
    filter:sepia(100%);
}
    <svg width="100" height="50">
      <defs>
        <filter id="sepia">
          <feColorMatrix type='matrix' values='0.30 0.30 0.30 0.0 0
                                               0.25 0.25 0.25 0.0 0
                                               0.20 0.20 0.20 0.0 0
                                               0.00 0.00 0.00 1 0'/>
        </filter>
      </defs>
      <rect x="0" y="0" width="100" height="50"/>
    </svg>

Firefox will now use the CSS filter, and Chrome the SVG filter. Of course, if you manage to make the SVG filter work the way you want, you could just stick with that. For me, I never managed to get exactly the effect I wanted, so I let Firefox use the better looking CSS filter.

Bug tracker for CSS filters on SVG elements in Chrome/ium: https://bugs.chromium.org/p/chromium/issues/detail?id=109224

Edit February 2021: CSS filters on SVG elements will start working in Chrome 89, if everything goes according to plan!

like image 171
leo Avatar answered Sep 18 '22 06:09

leo