javascripthtmlcssmobile

How to disable horizontal scrolling in an image?


I'm doing an animation-on-scroll page. At the moment, I'm optimizing it for mobile devices.

In case an element is bigger than the actual screen (e.g. bigger than a mobile screen), you're able to scroll in that element (e.g. you're able to scroll horizontally in an image). How can I block that? I've already found out that the e.g. actual x-scroll-position doesn't change when scrolling through an image horizontally.

Because of the animation, I'm not able to set any elements position to relative. Overflow-x: hidden doesn't work in my case.


Solution

  • Set the overflow-x: to hidden or overflow: hidden on the parent element to hide the view of the scroll bar for your image element which will be on the parents border-box. Then you can move your image element around relative to the parent element by positioning it using position: absolute;.

    .parent {
      width: 200px;
      height: 200px;
      overflow: hidden;
      position: relative;
    }
    
    .parent img {
      position: absolute;
      left: -220px;
      top: -30px;
    }
    <div class="parent">
      <img src="https://cdn.pixabay.com/photo/2017/06/05/18/22/nature-2374798_640.jpg">
    </div>
    
    <img src="https://cdn.pixabay.com/photo/2017/06/05/18/22/nature-2374798_640.jpg">