CSS Media Queries

Learn More - Media Queries

If the mere mention of "responsive design" and "media queries" makes your eyes roll back in your head, we're going to unlock a bit of the mystery. A media query is simply a set of css rules that are only used when a device screen is within a specific size range.

CSS
  1. @media screen and (max-width: 320px) {
  2. ...rules go here...
  3. }

The example above can be translated as "When the viewer's screen is 320 pixels or less, display the content according to these css rules..." This is actually pretty cool, because you can tweak, resize, move, hide, and change almost anything so it displays well on a variety of mobile devices and screen sizes.

Putting it Together

Want to play? In this scenario, the footer area has four divs that sit side by side on the desktop view. The last div holds a simple calendar, but you would rather not display that content to your visitors who are using a cell phone or a tablet.

The main css rules look like this:

CSS
  1. .footerBoxa {float: left; width: 23%; padding: 0; margin: 0 2% 0 0;}
  2. .footerBoxb {float: left; width: 23%; padding: 0; margin: 0 1% 0 1%;}
  3. .footerBoxc {float: left; width: 23%; padding: 0; margin: 0 1% 0 1%;}
  4. .footerBoxd {float: left; width: 23%; padding: 0; margin: 0 0 0 2%;}

Since a cell phone screen is pretty small, we need the footer boxes to sit on top of each other rather than side by side. So we are going to target any screen that is smaller than 481 pixels, resize the footer boxes, remove the float property on some, and hide the last one:

Media Query CSS
  1. @media screen and (max-width: 480px) {
  2. .footerBoxa {float: none; width: 100%; margin: 0;}
  3. .footerBoxb {float: none; width: 100%; margin: 0;}
  4. .footerBoxc {float: none; width: 100%; margin: 0;}
  5. .footerBoxd {visibility: hidden; display: none;}
  6. }

But visitors who are on tablets have a larger screen. You would like for them to see the first two boxes sitting side by side, have the third box display below the top two but be wider, and still hide the fourth box:

Media Query CSS
    1. @media screen and (min-width: 481px) and (max-width: 800px) {
    2. .footerBoxa {float: left; width: 49%; margin: 0 1% 0 0;}
    3. .footerBoxb {float: left; width: 49%; margin: 0 0 0 1%;}
    4. .footerBoxc {float: none; width: 100%; margin: 0;}
    5. .footerBoxd {visibility: hidden; display: none;}
    6. }

Yes, this is a simplified example, but hopefully it will give you an idea of how the media queries work to serve your content to devices with smaller screens.