Get the Effective Height and Width of the Browser When the Software Keyboard Appears in iOS Safari and Adjust the Layout

cssiOS
2023-07-16 11:02 (2 years ago)
Viewport Alchemy
Play a song themed on this article

When implementing a page layout with a fixed footer, there might be cases where the layout breaks when the software keyboard is displayed on iOS.

To resolve this, I made the maximum height of the layout a CSS variable and updated it continuously in the case of iOS.

:root {
  --visual-viewport-height: 100%;
}

body {
    height: var(--visual-viewport-height);
}
const w = window as any;
const refreshSize = () => {
  w.document.documentElement.style.setProperty('--visual-viewport-height', `${w.visualViewport.height}px`)
  w.scrollTo(0, 0)
}
w.mobileUIRefreshInterval = setInterval(refreshSize, 300)
refreshSize()

// To clear the condition
...
clearInterval(w.mobileUIRefreshInterval)

Additional Information

There's a -webkit-fill-available option for calculating 100vh correctly in iOS Safari

Although it wasn't suitable for this use case, it might be useful for other purposes, so I'll note it here.

body {
    height: 100vh;
}
@supports (-webkit-touch-callout: none) {
  body {
    /* The hack for Safari */
    height: -webkit-fill-available;
  }
}

Reference: Adjusting 100vh appropriately to display elements full-height on iOS

When the software keyboard is displayed, scrolling is forcibly enabled

Even if overflow: fixed is set on body, iOS forcibly enables scrolling when the software keyboard is displayed.

In this scenario, for a web app layout with a fixed footer, the user experience is not ideal.

There are several countermeasures, but I found that periodically executing window.scrollTo(0, 0) via setInterval is effective. Although there is a slight flickering issue when the window scrolls, it's practically stable and sufficient.

Please rate this article
Current rating: 5.0 (1)
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive