Search code examples
javascripthtmlcsssvgsvg-animate

Consistent filling of SVG's rectangles


How to make each of these squares filled with red colour consistently left to right; and when one filled with red, previous will have default colour?

#foo > rect {
  height: 32px;
  width: 32px;
}
<svg id=foo height=32 width=160>
  <rect x=0 y=0 />
  <rect x=64 y=0 />
  <rect x=128 y=0 />
</svg>

This animation must be repeatable.


Solution

  • Use CSS keyframes:

    #foo > rect {
      height: 32px;
      width: 32px;
      animation: anim 3s infinite;
    }
    
    #foo > rect:nth-of-type(1){
      animation-delay: 0s;
    }
    
    #foo > rect:nth-of-type(2){
      animation-delay: 1s;
    }
    
    #foo > rect:nth-of-type(3){
      animation-delay: 2s;
    }
    
    @keyframes anim{
      0% { fill: black; }
      50% { fill: red; }
      100% { fill: black; }
    }
    <svg id=foo height=32 width=160>
      <rect x=0 y=0 />
      <rect x=64 y=0 />
      <rect x=128 y=0 />
    </svg>