Search code examples
cssmedia-queries

Why do I need to add an extra pixel for a max height when using media queries?


I have this here code running on 3840x2160 at 225% zoom

#d1 {
  height: 400px;
  width: 275px;
  background-color: hotpink;
}

@media (max-height: 850px) {
  #d1 {
    height: 400px;
    width: 275px;
    background-color: green;
  }
}

@media (max-height: 818px) {
  #d1 {
    height: 400px;
    width: 275px;
    background-color: purple;
  }
}
<div id="d1"></div>

When I don't have the bookmark bar open, the d1 will have background color of hotpink, but when I check the window height it shows 850px, when I show the bookmark bar, the window height is 818px and then d1 background color goes to green.

Now if I add 1 more pixel to the max height

@media (max-height: 851px) {
    #d1 {
        height: 400px;
        width: 275px;
        background-color: green;
    }
}

@media (max-height: 819px) {
    #d1 {
        height: 400px;
        width: 275px;
        background-color: purple;
    }
}

Then when I hide the bookmark bar, I get the background color of green and when I show the bookmark bar, the background color goes to purple.

So my question is, why do I need to add an extra pixel to the max height to get this to work properly?


Solution

  • Browsers tend to... not use whole numbers.

    What's probably happening is even though dev tools SAYS your window is 850px tall, it's probably 850.25px tall.

    As such, since 850.25px is bigger than 850px, the media query doesn't trigger.

    (Keep in mind that your entire viewport is being divided by 225% since you're zoomed in, so it's very unlikely that the math will come out to a whole number...)