csssassmedia-queries

media queries not working on specific pixel width CSS/SASS


I have these 2 media queries

@media all and (max-width: 1199px) {
    // CSS
}

@media all and (min-width: 1200px) {
    // CSS
}

When testing this out it works well, but when testing it out, only in 1199px the CSS does not work, but it works on 1px to 1198px and from 1200px

Can I have some insights?

Inspecting, changing the breakpoints, tested on different browsers


Solution

  • I can repro, when my zoom level is odd, like e.g. 110% (on a retina monitor, so that's a dPR of 2.222).

    const frame = document.querySelector("iframe");
    const input = document.querySelector("input");
    
    input.oninput = e => frame.style.width = input.value + "px";
    input.oninput();
    <iframe srcdoc="
    <style>
    body { height: 100vh }
    @media all and (max-width: 1199px) {
       body { background: red }
    }
    
    @media all and (min-width: 1200px) {
       body { background: green }
    }
    </style>
    <h1>Hello<h1>
    "></iframe>
    
    Frame size: <input type="number" value="1200">

    This happens because both min-width and min-height are inclusive, so when on an odd zoom the actual width is not an integer pixel value, it will fall in between your 2 values.

    To avoid that, you can use the media query range feature syntax value < width or value <= width which allows you to define both inclusive and exclusive ranges:

    const frame = document.querySelector("iframe");
    const input = document.querySelector("input");
    
    input.oninput = e => frame.style.width = input.value + "px";
    input.oninput();
    <iframe srcdoc="
    <style>
    body { height: 100vh }
    @media all and (width < 1200px) {
       body { background: red }
    }
    
    @media all and (width >= 1200px) {
       body { background: green }
    }
    </style>
    <h1>Hello<h1>
    "></iframe>
    
    Frame size: <input type="number" value="1200">