26

I created a modal. When the modal is open I'm stopping the scroll on Desktop with overflow:hidden; to the <body>. It's working.

But it's not working on my iPhone 6s Mobile Safari.

How can I prevent scrolling when the modal is open in mobile safari?

hzhu
  • 3,759
  • 5
  • 29
  • 39

2 Answers2

39

Combine it with position: fixed to do this on iOS…

overflow: hidden;
position: fixed;
matharden
  • 757
  • 6
  • 15
  • 16
    Sorry to resurrect an old thread, but this answer works only if the modal is being triggered while the page is scrolled all the way to the top. If the page is scrolled down at all then setting "position: fixed" will scroll you back to the top before triggering the modal instead of leaving you where you were when you triggered the modal. Is there a solution that addresses this as well? – Barak Gall Aug 29 '16 at 20:57
  • 1
    @0sin Set the body's `height` to its `scrollHeight`, then make the children `fixed` and use `transform: 'translateY(-' + body.scrollTop + 'px)'` on them – aleclarson Jun 01 '17 at 02:37
  • 1
    @aleclarson not hacky at all, gotta love iOS – br4nnigan Jun 27 '18 at 12:17
  • 1
    Thanks - that sorted it for me! When will the trillion dollar company finally pull their finger out and sort out all these crappy IOS bugs? I'm fed up having to do hacks around issues that shouldn't even be issues *hmmmf* – Andrew Newby Dec 03 '18 at 15:02
  • Just to say that the "position: fixed" would cause black box on the bottom of the website on iPhoneX, and probably any build later than that. – Terry Windwalker Dec 28 '21 at 17:11
31

There isn't (to my knowledge) a great way to accomplish this with CSS without repercussions on the UX.

While it's Javascript, and not CSS, the best way I've found to do this is the following:

// Disable scrolling.
document.ontouchmove = function (e) {
  e.preventDefault();
}

// Enable scrolling.
document.ontouchmove = function (e) {
  return true;
}
AsLittleDesign
  • 345
  • 3
  • 4