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

css iOS
2023-07-16 20:02 (1 years ago) ytyng

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.

Currently unrated

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011