Alessandro Marchisio
Alessandro Marchisio

Reputation: 545

left-right movement.. css only very generic

I would like to write a generic css animation to move a div right and left, touching the edges of the container .. to be applied in a simple way to any div of which I know nothing except that it has an absolute positioning.

The problem is that simply putting left at 0% and then at 100% .. for a few moments disappears, I should use something like calc (100% -width) .. Putting a 50% keyframe is almost like I would like, but there's a slowdown and it is not very fluid and linear ... Any suggestions, considering that I do not know how long my div will be, and i dont work with js/jquery, but only with css..?

https://codepen.io/alemarch/pen/vrvgMo

 @keyframes destraSinistra {
  0% {
    left: 0%;
    color: black;
    right: unset;
  }
  50% {
    left:50%;
    right: 50%;
  }

  100% {
    left:unset;
    right: 0px;
    color: green;
  }
}


#div1 {
  position: absolute;
  border: solid 1px lightgray;
  width: 100px;
  top: 200px;
  height: 30px;
  background-color: lightgreen;
  animation-name: destraSinistra;
  animation-duration: 4s; 
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-direction: alternate-reverse 
}

Upvotes: 7

Views: 1592

Answers (1)

Temani Afif
Temani Afif

Reputation: 272842

Use transform combined with left or right to avoid adding any fixed value:

@keyframes destraSinistra {
  0% {
    left: 0;
  }
  100% {
    left: 100%;
    transform:translateX(-100%);
  }
}


#div1 {
  position: absolute;
  border: solid 1px lightgray;
  width: 100px;
  height: 30px;
  background-color: lightgreen;
  animation: destraSinistra 1s linear infinite alternate
}
<div id="div1"></div>

Upvotes: 5

Related Questions