window.innerWidth in JS doesn't equal to `width:100%` in css

929 Views Asked by At

I am creating a webpage on mobile, which will fit 100% width of the screen.

However, when I created some elements with JavaScript and set the width to window.innerWidth, they would be much wider than the static elements that set width: 100% in CSS. (on iPhone 6(s))

The width: 100% sets these elements to 375px, which I think is right, since the screen resolution is 1334 x 750. However the window.innerWidth is 488px, for whatever reason I really don't understand.

Is this a bug of the browser I am testing, or I miss something for retina screen?

By the way, I use width:480px;max-width:100% to set the static elements. The view-port meta is like <meta name="viewport" content="width=device-width, initial-scale=1.0">

1

There are 1 best solutions below

0
On

Pixel ratio and sidebars can cause the innerwidth of window to be different depending on the device. If you need to check window width in javascript so your media queries match up. Use the window.matchmedia function.

JS

  if ( window.matchMedia('max-width:800').matches ){
        console.log('tablet mode');
  }