Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
}
like image 362
Alessandro Marchisio Avatar asked Jun 29 '18 10:06

Alessandro Marchisio


People also ask

What is the effect of CSS property animation direction with value as alternate-reverse?

The animation plays backwards each cycle. In other words, each time the animation cycles, the animation will reset to the end state and start over again. Animation steps are performed backwards, and timing functions are also reversed. For example, an ease-in timing function becomes ease-out .

How do I change my position to left in CSS?

If position: absolute; or position: fixed; - the left property sets the left edge of an element to a unit to the left of the left edge of its nearest positioned ancestor. If position: relative; - the left property sets the left edge of an element to a unit to the left/right of its normal position.


1 Answers

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>
like image 157
Temani Afif Avatar answered Oct 10 '22 20:10

Temani Afif