Random “start point” for CSS keyframes animation

前端 未结 4 1392
[愿得一人]
[愿得一人] 2021-02-14 06:52

I have a list of boxes with a background image that scrolls vertically with:

@keyframes movie {
   0% { background-position: 50% 5%; }
   50% { background-positi         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 07:33

    This can be done with pure CSS, without writing (or generating via SCSS etc), using a combination of:

    • A negative animation-delay to change the start time of the animation
    • Multiple nth-child or nth-of-type rules to apply formulas that will 'randomize' rule application
    movie.nth-child(2n) { animation-delay: -10s }  
    movie.nth-child(2n+1) { animation-delay: -30s }  
    movie.nth-child(3n) { animation-delay: -20s; }  
    movie.nth-child(5n) { animation-delay: -40s }  
    movie.nth-child(7n) { animation-delay: -15s }  
    {etc}
    

    Using just the first 2 rules gives alternating rules (e.g. even/odd rows in a table). Notice the second rule which has a +1 offset - this is important if your class (movie) doesn't have an appropriate default for the rule you are changing (0 by default anyways for animation-delay).

    Using nth-child(n) formulas with prime multiples of n makes an effective pattern length equal to the product of all your prime factors (e.g. 2*3*5*7 = 210 elements before repeating).

    li {
      animation: movie 5s linear infinite;
    }
    @keyframes movie {
      20% { color: white }
      40% { color: black }
    }
    li:nth-child(2n-1) {
      background-color: lime;
      animation-delay: 1s;
    }
    li:nth-child(2n) {
      background-color: orange;
      animation-delay: 2s;
    }
    li:nth-child(3n) {
      background-color: yellow;
      animation-delay: 3s;
    }
    li:nth-child(5n) {
      background-color: magenta;
      animation-delay: 5s;
    }
    li:nth-child(7n) {
      background-color: aqua;
    }
    • 0
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    For further randomization, you could create a second set of rules with slightly different n multiples/offsets and change the animation-duration (or any other rule really).

提交回复
热议问题