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.
<!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 ></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>
CodePudding user response:
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 ></span>
CodePudding user response:
The media query is working perfectly OK.
Your problem is the rather strange way you are finding the width of the viewport.
In fact, you aren't.
In this expression:
let width = windowEl.innerWidth || document.documentElement.clientWidth ||document.body.clientWidth;
First windowEl.innerWidth is evaluated. It's not defined - innerWidth doesn't apply here. So the next value is evaluated.
Then I think you have forgotten that browser's add default margins.
At no point do you look at the actual viewport width which can be obtained through window.innerHTML