Search code examples
cssmedia-queriesresponsive

My responsive media-query doesn't show neither mobile or desktop view


I'm building a different view for mobile and desktop, and have problem with the limit of 500px. When the screen has exactly a 500px width, my screen doesn't show not mobile nor desktop view.

.desktop-view{
  background-color: blue;
  color : yellow
}

.mobile-view{
  background-color: yellow;
  color : blue;
}


@media (min-width: 500px) {
    section.mobile-view{
      display: none;
  }
    
}

@media (max-width: 500px) {
    section.desktop-view{
      display: none;
  }    
}
<div>
      
      <section class="desktop-view">
        This is the desktop view
      </section>

      <section  class="mobile-view">
        This is the mobile view
      </section>

</div>

If I change one 500px by 501px, I have both lines. I feel I tried all hacky combination without success.


Solution

  • At exactly 500px, both of your media are triggered so none of your views are shown. You could display:none your desktop view by default and set it as block if the screen is larger than 500px.

    /* everything, or mobile only if overridden in media queries */
    .mobile-view{
      background-color: yellow;
      color : blue;
    }
    section.desktop-view{
      display: none;
    }
    
    /* desktop */
    @media (min-width: 500px) {
      section.mobile-view{
        display: none;
      }    
      section.desktop-view{
        display: block;
        background-color: blue;
        color : yellow
      } 
    }
    <div>
      <section class="desktop-view">
        This is the desktop view
      </section>
      <section  class="mobile-view">
        This is the mobile view
      </section>
    </div>