Search code examples
htmlcssmedia-queriescss-animations

css animation not triggering after media query


i have a list that looks like this

<ul class="timeline-container">
   <li class="timeline-item-container">
       <div class="timeline-item></div>
   </li>
   <li class="timeline-item-container">
       <div class="timeline-item></div>
   </li>
</ul>

I declare the 2 animations

    @keyframes slideLeft
    {
        from {
            transform: translateX(1000px);
        }

        to {
            transform: translateX(0);
        }
    }

    @keyframes slideRight
    {
        from {
            transform: translateX(-1000px);
        }

        to {
            transform: translateX(0);
        }
    }

Then on my css i have this:

.timeline-item
{
    animation: slideRight .6s ease both;

    @media (max-width:767px)
    {
        animation: slideLeft .6s ease both;
    }
}

So this works perfect, all the items in my list slide in from the right when the screen is smaller than 767px and from the left when its any bigger. when i resize the screen, the animation plays again.

Now i want every odd item in the list to slide in from the right when the screen is bigger than 767px so I add this:

.timeline-item-container:nth-child(even) .timeline-item
{
   @media (min-width:767px)
   {
        animation: slideLeft .6s ease both;
   }
}

This works if i refresh the page but if i resize the screen, the animation doesnt play. It should play the animation when the screen resizes like before

I know the animation is there because if i refresh it, it plays, just not after i resize the screen

Any help is appriciated

https://jsfiddle.net/7pk6yncd/


Solution

  • I think the only way is to define the same animation twice under different names. Actually the animation you are using is the same so the media query will not trigger it again.

    .box {
      background:red;
    
      animation:fromLeft 2s linear forwards;
    }
    
    @media all and (max-width:600px) {
    .box {
      background:blue;
      display:block;
      animation:fromLeft-alt 2s linear forwards;
    
    }
    
    }
    
    @keyframes fromLeft {
       from {
         transform:translateX(-100%);
       }
    }
    @keyframes fromLeft-alt {
       from {
         transform:translateX(-100%);
       }
    }
    <div class="box">
      some content
    </div>