search

Home  >  Q&A  >  body text

Move the image from left to right and then from left to right again

I'm writing CSS for some images, basically what I want to achieve is, there is an image that should move from the left to the right and when it reaches the right end it should appear left again etc. I was able to use the following code to achieve this.

@keyframes slideAnimation {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(100%);
  }
}

.row-1 {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  width: 100%;
  height: 100%;
}

.image-container {
  position: absolute;
  top: 4%;
  width: 100vw !important;
  overflow: hidden;
  animation: slideAnimation 18s linear infinite;
}
<div class="row-1">
  <div class="image-container">
    <img class="img" src="/src/assets/image.svg" alt="img">
  </div>
</div>

This works on desktop, not mobile CSS, it adds scrolling to my page even though the image comes out of the left again when it reaches the right, but the width of the image container is 100vw and the image is at the beginning of the container when When the image reaches the far right, a scroll occurs due to the container width, which affects other absolute elements on the page, can I somehow disable that scrolling, or use some different way to achieve the same effect, as it The same goes for other absolute elements that affect me.

P粉739079318P粉739079318453 days ago517

reply all(1)I'll reply

  • P粉973899567

    P粉9738995672023-09-08 11:37:01

    The problem you are facing is due to the animated element moving outside the viewport, causing the page to scroll. One way to prevent this is to hide the overflow on the parent container. However, since you mentioned that this affects other absolute elements on the page, another approach might be to use the CSS transform property instead of changing the left or right properties.

    @keyframes slideAnimation {
      0% {
        transform: translateX(-100%);
      }
      100% {
        transform: translateX(100%);
      }
    }
    
    .row-1 {
      overflow: hidden;
      position: relative;
      width: 100%;
      height: 100%;
    }
    
    .image-container {
      position: absolute;
      top: 4%;
      width: 100%;
      animation: slideAnimation 18s linear infinite;
    }

    slideAnimation keyframe uses translateX to move the image from left to right. The image starts at the screen (-100%) and moves to the right side of the screen (100%). Overflow: hide on the .row-1 class will prevent any horizontal scrolling caused by animation.

    This will give you the effect you want without causing any unwanted scrolling

    reply
    0
  • Cancelreply