animation + transition test (very impotant info about transitions and margin animations)

by ShaCP

HTML

<div id="container">
  <div id="one">
  </div>
</div>

CSS

/* IMPORTANT: if you animate using margins, you gotta
watch for margin collapse. It will mess up the animation.
If you have a div inside body, and body has 8px margin, and you
play an animation that takes the div from translate 0 and margin-top
100px to 0 margin and translateX(100), the div will reach the top then slide to the
end of the X translation. This is because once it reaches the top, it still has the 8px
of the margin it shares with body. So technically, it will keep moving down to
0 margin but it can't keep moving up because it's already 
touching body, so all you see is the translateX movement. Weirdly, if you 
put a border around body, margin collapse doesn't mess up the animation..*/

#one {
  width: 100px;
  height: 100px;
  background-color: lightskyblue;
  position: relative;
  animation: 5s linear forwards;
  transition: margin-top linear 0.5s;
  margin-top: 100px;
  /* transform: translate(0, 100px); */
}

#container {
  /* margin: 0; */
    display: inline-block;
    /* border: 1px solid black; */
    background-color: red;
}

#one.play {
  animation-name: move;
}

/* div:nth-child(2) {
  width: 100px;
  height: 100px;
  background-color: lightgreen;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
} */

/* try hovering while the animation is running and you'll
see it will ignore the transition; this is because the 
animation below also affects margin-top, and it will override
the transition; when yo hover, it will act as if it had a 5vh
margin from the beginning and the element will move to the position
it would be at that point in the animation. So every time you hover
the element will move less*/
div:hover {
  /* margin-top: 5vh; */
}

/* @keyframes move {
  from {
     transform: translate(0, 100px);
  }
  
  to {
    transform: translate(300px, 0);
  }
} */

@keyframes move {
  to {
    transform: translate(300px);
    margin: 0;
  }
}

JavaScript

one.addEventListener("click", (e) => e.target.classList.toggle("play"))
/* one.addEventListener("animationend", (e) => e.target.classList.toggle("play")) */