Skip to content

Instantly share code, notes, and snippets.

@searls
Last active July 26, 2021 02:14
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save searls/e0bdcbdc35fb92e1a359696aa2700933 to your computer and use it in GitHub Desktop.
Save searls/e0bdcbdc35fb92e1a359696aa2700933 to your computer and use it in GitHub Desktop.

Fix absolutely positioned divs when people turn their phones sideways

The problem

In Safari, if you have a layout container that's absolutely positioned to take up, at a minimum, its whole container (which isn't unheard of in "appey" internet home page thingies) using CSS like this:

.absolutely
  position: absolute
  min-height: 100%
  min-width: 100%

And the page looks like this:

And then you turn your phone like this:

And then you turn your phone back:

13 years of developing orientation change management into iOS has not been enough to repaint a browser window, apparently.

The fix

JavaScript!

const resetAbsolutePositioningAfterOrientationChangeBecauseIosIsLiterallyBroken = () => {
  if (!isIos()) return
  window.addEventListener('orientationchange', () => {
    document.querySelectorAll('.absolutely').forEach(node => {
      node.classList.remove('absolutely')
      setTimeout(() => {
        node.classList.add('absolutely')
      }, 150)
    })
  })
}

const isIos = () =>
  _.includes([
    'iPhone', 'iPad', 'iPod',
    'iPhone Simulator', 'iPad Simulator', 'iPod Simulator'
  ], navigator.platform)


const main = () => {
  // app start stuff…
  
  // this bullshit: 
  resetAbsolutePositioningAfterOrientationChangeBecauseIosIsLiterallyBroken()
}

150ms was, of course, the shortest timeout I could set for the class to be added before the layout was broken by the orientation change. Fortunately, it's barely perceptible by the user in my case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment