The device I am testing with is iPhone 11, on Chrome version 87.0.4280.77. I have found out that after rotating your device, bothdocument.documentElement.clientWidth
and window.innerWidth
are incorrect. Sometimes it lags behind, sometimes it outputs values that are smaller or greater than either one of your phone's dimension. Often both the clientWidth
and innerWidth
displays the same incorrect information, but at times they can be different. I have also tested Safari, Firefox, Edge, and Opera, but they all came out correctly.
Here is a minimal reproducible example:
const displayInfo = () => document.querySelector('.display-info').innerText = `clientWidth: ${document.documentElement.clientWidth}; innerWidth: ${window.innerWidth};`
displayInfo()
const handler = () => {
const afterOrientationChange = () => {
displayInfo()
window.removeEventListener('resize', afterOrientationChange)
}
window.addEventListener('resize', afterOrientationChange)
}
window.addEventListener('orientationchange', handler)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p class="display-info"></p>
</body>
<script src="index.js"></script>
</html>
For instance, my phone's initial dimension should be 414 and 800. Here's what happens when I keep on rotating my phone back and forth (starting with portrait, rotating once after each result):
- clientWidth: 414; innerWidth: 414;
- clientWidth: 414; innerWidth: 414;
- clientWidth: 318; innerWidth: 318;
- clientWidth: 896; innerWidth: 896;
- clientWidth: 318; innerWidth: 318;
- clientWidth: 896; innerWidth: 318;
- clientWidth: 318; innerWidth: 318;
- clientWidth: 896; innerWidth: 896;
and so on.
Is this a known problem? Is there any way to work around this? It affects my CSS as well as it sometimes renders the website incorrectly.