skip to Main Content

I need to animate a div such that it move left to right and change its color when it hits the edge of screen. So far I have come to a point like this
<div class="move-me">no steps</div>

.move-me {
  display: inline-block;
  padding: 20px;
  color: white;
  position: relative;
  margin: 0 0 10px 0;
  animation: move-in-steps 8s infinite;
}

body {
  padding: 20px;
}

@keyframes move-in-steps {
  0% {
    left: 0;
    background: blue;
  }
  100% {
    left: 100%;
    background: red;
  }
}

where I can smoothly move the div, but the color change is also smooth while I need it to be sharp.

How can I achieve this without using javascript?

2

Answers


  1. Make a very close frame where color is the same for non-smooth color transition. With respect to the edge of the screen, translate the element -100% in the x-axis. Try the following code.

    .move-me {
      display: inline-block;
      padding: 20px;
      color: white;
      position: relative;
      margin: 0 0 10px 0;
      animation: move-in-steps 3s;
      animation-fill-mode: forwards;
    }
    
    body {
      /* Edges of the screen */
      border-right: 1px solid black;
      border-left: 1px solid black;
      height: 200px;
    }
    
    @keyframes move-in-steps {
      0% {
        left: 0;
        background: blue;
      }
      99% {
        background: blue;
      }
      100% {
        transform: translate(-100%, 0);
        background: red;
        left: 100%;
      }
    }
    <div class="move-me">no steps</div>
    Login or Signup to reply.
  2. You could put two animations on the element. The second animations just changes the color in the end:

    /* added change-color at the end as additional-animation which finishes a little bit earlier */
    .move-me { [...] animation: move-in-steps 8s infinite, change-color 8s infinite; }
    
     body { padding: 20px; }
    
     @keyframes move-in-steps {
         0% { left: 0;   }
         100% { left: 100%;  }
     }
    
     /* Animation runs parallel, the color-change happens at the end in the last 5% of the 8 seconds */
     @keyframes change-color {
        95%  { background: blue; }
        100% { background: red; }
     }
    

    It is not completely sharp at the end but you have to play with the numbers (percentage and seconds).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search