Home > other >  Why "screen.height" works fine when using Chrome' DevTool to simulate mobile devices,
Why "screen.height" works fine when using Chrome' DevTool to simulate mobile devices,

Time:09-23

The screen.height I am talking about is described in enter image description here

By "works fine", I mean when simulating a mobile device, like setting device to be iPhone X as shown above and displaying in landscape mode, the UI elements are hidden correctly due to screen.height < 560 = true.

However, on real mobile devices like a real iPhone X, the UI elements don't get hidden, which I guess is because that it is always screen.height < 560 = false, even if it is in landscape mode.

I am wondering why is that... Why iPhone X in DevTool has a different height from a real iPhone X?

Is the simulation in Chrome DevTool not accurate? Or is it because screen.height doesn't return the correct value on mobile device?

Any hints would be appreciated!

CodePudding user response:

It might be because you are missing the response meta tag. Try adding this to your head tag:

<meta name="viewport" content="width=device-width, initial-scale=1">

CodePudding user response:

That's because the simulator takes the screen size according to the dimensions that you are setting there. But in reality, screen.height takes the height size of the whole screen, including elements that are outside of the viewport in the device. You should use window.innerHeight to get an accurate height size.

screen.height: The Screen.height read-only property returns the height of the screen in pixels.

window.innerHeight: The read-only innerHeight property of the Window interface returns the interior height of the window in pixels, including the height of the horizontal scroll bar, if present. The value of innerHeight is taken from the height of the window's layout viewport. The width can be obtained using the innerWidth property.

If you log in your console screen.height and window.innerHeight on the simulator, you will get the same size. If you do this in the normal viewport (deactivating the simulator), you will get different values.

More info: Screen Height - Window InnerHeight

  • Related