htmlcssmedia-queries

Why is media query applying to a smaller value than what I set?


I am using js to monitor the mouse xy and when I shrink the window, the media applies to a value that I did not ask. What can be causing this calculus error? Is it the browser-side scrollbar? I am using Brave browser to test this, and it doesn't matter if I try "min-width" or "max-width", the value I set, it only applies less than it, as the images show below.

enter image description here enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <style>
    body {
      background-image: linear-gradient(45deg, #222, #444, black);
      min-height: 100vh;
    }

    @media only screen and (max-width: 1000px) {
      body {
        background-image: linear-gradient(45deg, purple, yellow, black);
      }
    }
  </style>
</head>
<body>
  <span class="window-properties"></span>
  <script>
    let windowEl = document.querySelector('.window-properties')
    setInterval(() => {
      let width  = windowEl.innerWidth || document.documentElement.clientWidth || 
      document.body.clientWidth;
      let height = windowEl.innerHeight|| document.documentElement.clientHeight|| 
      document.body.clientHeight;
      windowEl.innerHTML = `${width}, ${height}`
    }, 1)
  </script>
</body>
</html>

Solution

  • I think your problem are the margins and paddings that are taken into account in your calculations.

    Take a look at this example. I have added a couple of css lines to remove the paddings and margins, and then it seems to work well.

    let windowEl = document.querySelector('.window-properties')
    setInterval(() => {
      let width = windowEl.innerWidth || document.documentElement.clientWidth ||
        document.body.clientWidth;
      let height = windowEl.innerHeight || document.documentElement.clientHeight ||
        document.body.clientHeight;
      windowEl.innerHTML = `${width}, ${height}`
    }, 1)
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      background-image: linear-gradient(45deg, #222, #444, black);
      min-height: 100vh;
    }
    
    @media only screen and (max-width: 1000px) {
      body {
        background-image: linear-gradient(45deg, purple, yellow, black);
      }
    }
    <span class="window-properties"></span>