Angelos Chalaris Angelos Chalaris - 2 years ago 74
CSS Question

Media queries behaving weirdly around breakpoint

I've been trying to create some responsive hiding classes in CSS, only to realize that my

@media
queries are behaving very weirdly around breakpoints.

What I want to create



I want to create two classes, that have the following functionality:


  • .hidden-sm
    should be hidden when the viewport width is less than 768px

  • .hidden-md
    should be hidden when the viewport width is greater than or equal to 768px



What I have tried so far



My original solution was the following:

@media screen and (max-width: 767px) {
.hidden-sm { display: none !important; }
}

@media screen and (max-width: 1279px) and (min-width: 768px) {
.hidden-md { display: none !important; }
}


However, this code ends up showing both
.hidden-sm
and
.hidden-md
(or hiding none of them if you prefer) at exactly 768px.

Another thing I tried was this:

@media screen and (max-width: 768px) {
.hidden-sm { display: none !important; }
}

@media screen and (max-width: 1279px) and (min-width: 768px) {
.hidden-md { display: none !important; }
}


But this one ended up hiding both
.hidden-sm
and
.hidden-md
at exactly 768px.

I think I have a pretty decent grasp of
@media
queries, but this specific problem is confusing to me. I would appreciate a working solution, as well as an explanation of why these solutions don't work as expected.

P.S. I know
!important
is not the best practice, but I think it's quite necessary for my specific needs, which might not be obvious in this example.


Update: For whatever odd reason, if I change the first piece of code to
768px
and
769px
respectively, it works, only the breakpoint is one pixel after the desired one. Why?

Answer Source

I can't really replicate your issue so I've rewritten the media queries in a simple format to check that the logic works.

I'm not using a max width and a min width, just using one (as it's all that's needed in most cases)

@media(max-width: 767px){
    body {
        background-color: red;
    }
}

@media(min-width: 768px){
    body {
        background-color: green;
    }
}

Which can also be tested here - https://jsfiddle.net/3dLyhr8c/

The fact this works across my devices I can only assume that you have an issue with your browser zoom or similar :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download