Search code examples
cssmedia-queries

the 1px gap when using min and max with media queries



I have been dealing with an issue with min and max width usage in the last few years with websites I am developing for the company I work for.

Though I can easily get around this by just changing the breaking points, it annoys that I don't know why it is happening and I keep walking into this issue after the websites have had some modifications.

So the issue is probably most know for the non-100% gap. This issue though is not related to screen zoom but rather just a breakpoint that isn't functioning like would be expected from it or at least how I expect it to work.

(For the example I put together a situation this happens in. There are some situations that something along these lines happens in the development process)

For this example I have 2 div's with classes test1 and test2 respectively.

<div class="test1">
  test 1
</div>
<div class="test2">
  test 2
</div>

Both div's should be hidden normally but in certain situations you would want them to show. So lets say we get to the situation where we want to show test2 on desktop and test1 on mobile. That would result in a CSS like below

@media (min-width: 768px) {
  .test2{
    display: block;
  }
}
@media (max-width: 768px) {
  .test1{
    display: block;
  }
}

Now comes the weird part.
As soon as I show the website and start resizing the page both will be visible at exactly 768px width which is not the desired result.

The reason I don't understand why this happens is that when I look on the internet I only read that a media query basically does the following (as far as I understand it)

For min-width:
IF the viewport is equal to or bigger than the min-width, apply the styling in the media query

For max-width:
IF the viewport is lesser than or equal to the max-width, apply the styling in the media query

If you would practically apply this you would think that the moment the viewport reaches the 768px breakpoint both media queries would trigger and hide the test2 div and show test1.

Hope someone could shed some light on this for me.

I also made a codepen example

Kind regards.


Solution

  • Because you have the same breakpoint for min/max-width.

    That's why when min-width is used it's added a pixel or other way around subtracting a pixel to max-width.

    With this in mind, you have 2 options:

    First

    @media (min-width: 769px) {
    .test2{
        display: block;
      }
    }
    @media (max-width: 768px) {
      .test1{
        display: block;
      }
    }
    

    Second

    @media (min-width: 768px) {
    .test2{
        display: block;
      }
    }
    @media (max-width: 767px) {
      .test1{
        display: block;
      }
    }
    

    You can read about media queries order matters?