Hacker News new | ask | show | jobs
by panstromek 695 days ago
It's something like this (I just quickly took this from my project, not sure if it works in this form now). This one uses the defs/use trick to reuse a path, but you can also just put two different svgs next to each other and not use the defs/use at all.

The icon:

  <!--   the icon width is 2x wider, to accommodate both 26x26 variants  -->
  
  <svg xmlns="http://www.w3.org/2000/svg" width="52" height="26">
    <defs>
      <!-- here's the icon defined, you can basically put anything here and
           mark it with an id (you can even use another svg) -->
      <path id="icon" path="..."/>
    </defs>
  
    <!-- first variant with no fill -->
    <use stroke="#fff" href="#icon"/>
  
    <!-- second variant with fill, shifted by 26 (dimensions of the icon) -->
    <use x="26" fill="#00ACA0" stroke="#00ACA0" href="#a"/>
  </svg>
  
HTML:

    <!-- make sure you use dimensions of the single variant -->
  <img src="icon.svg" width="26" height="26" class="hover-icon">
  
CSS:

  .hover-icon {
    /* make sure that only first block of the image is visible */
    object-fit: cover;
    object-position: left;
  }
  .hover-icon:hover {
    object-position: right;
  }
1 comments

Sandbox (with fixes): https://codesandbox.io/p/sandbox/pan-stromek-svg-object-posi...

Btw, for such simple re-colouring I'd probably rather used CSS hue shift filter or similar effect, and kept the SVG "dumb". But for having different shapes or geometric properties this approach is indeed nifty.

Yes, I do that, too. The benefit of using the sprite system is that it's pretty general, so once you have some CSS for it, it's easy to keep adding new icons. CSS filters are usually more special for each case, but I use them too (mostly for brightness and greyscale things that are repeated on multiple places, e.g. tabs or disabled state).