Search code examples
htmlcsscss-variablescss-counter

how to use same @keyframes and @property twice for more than 1 div?


as you see in this simple css counter, https://codepen.io/bgbos/pen/pobZvwJ we have 4 div's each of them has a different initial value which must be appear at the end of animation but it don't , it all stop at one value

and this is the original one with just on value working good , CSS & HTML

@property --num {
  syntax: "<integer>";
  initial-value: 984;
  inherits: false;
}

#twitter {
  animation: counter 3.9s infinite alternate ease-in-out;
  animation-iteration-count:1;
  counter-reset: num var(--num);
  
  
}
#twitter::before {
  content: counter(num);
}

@keyframes counter {
  from {
    --num: 0;
  }
  to {
    --num: 100;
  }
}



@property --num {
  syntax: "<integer>";
  initial-value: 402;
  inherits: false;
}

#instagram {
  animation: counter 3.9s infinite alternate ease-in-out;
  animation-iteration-count:1;
  counter-reset: num var(--num);
  
  
}
#instagram::before {
  content: counter(num);
}


@property --num {
  syntax: "<integer>";
  initial-value: 254;
  inherits: false;
}

#facebook {
  animation: counter 3.9s infinite alternate ease-in-out;
  animation-iteration-count:1;
  counter-reset: num var(--num);
  
  
}
#facebook::before {
  content: counter(num);
}



@property --num {
  syntax: "<integer>";
  initial-value: 610;
  inherits: false;
}

#youtube {
  animation: counter 3.9s infinite alternate ease-in-out;
  animation-iteration-count:1;
  counter-reset: num var(--num);
  
  
}
#youtube::before {
  content: counter(num);
}
<div id="twitter" ></div>
<div id="instagram" ></div>
<div id="facebook" ></div>
<div id="youtube" ></div>

https://codepen.io/CarterLi/pen/NWNJvPE that i was trying to edit .

sorry if there are mistakes , just beginner . appreciate your help .


Solution

  • The value need to be inside the element and your code can be simplified like below:

    #twitter,
    #instagram,
    #facebook,
    #youtube{
      animation: counter 3.9s  ease-in-out;
      counter-reset: num var(--num);
    }
    
    #twitter::before,
    #instagram::before,
    #facebook::before,
    #youtube::before{
      content: counter(num);
    }
    
    #twitter { --num:984; }
    #instagram { --num:402; }
    #facebook { --num:254; }
    #youtube { --num:610; }
    
    @property --num {
      syntax: "<integer>";
      initial-value: 0;
      inherits: false;
    }
    
    @keyframes counter {
      from {
        --num: 0;
      }
    }
    <div id="twitter" ></div>
    <div id="instagram" ></div>
    <div id="facebook" ></div>
    <div id="youtube" ></div>