Search code examples
media-queries

CSS media queries (mobile, tablets, and screens)


I'm trying to make the move to being a Responsive developer (instead of a fixed one). I've been trying to understand media queries as of late and having some confusion. The test is simple:

I want to change the body background color to red for mobile, yellow for tablets, green for wide screens. The following code demonstrates this (for the most part). The issue I'm having is when the width drops below 480px (30em's), the background reverts back to its default css (background turns red to white). Now.., my small mind tells me "ohh I'll just make a

     @media only screen and (min-width:1em) { body { background:red;} } 

... that will fix the problem!"

This however seems wrong and unintuitive. Does anyone know the proper way to achieve this simple task?

/*
==========================================================================
 MOBILE (min-width 480px)
========================================================================== */
   @media only screen and (min-width: 30em) {

    body { background:red; font-size:.75em; }

}


/* 
==========================================================================
 TABLETS (min-width 768px)
========================================================================== */
@media only screen and (min-width: 48em) {

body { background:yellow;  font-size:.85em; }

}

/* 
==========================================================================
 SCREENS (min-width 1140px)
========================================================================== */
@media only screen and (min-width: 71.25em) {

body { background:green;  font-size:1em; }

}

Solution

  • If I were you, I'll revert the whole CSS into a max-width. Something like max-width: XX is a smartphone, max-width: YY is a tablet, else is a screen. So, it'll turn into something like this:

    body { background:green;  font-size:1em; }  
    
    @media only screen and (max-width: 71.25em) {
      body { background:yellow;  font-size:.85em; }
    }
    
    @media only screen and (max-width: 48em) {
      body { background:red; font-size:.75em; }
    }