Media Queries

Media queries enable us to create a responsive experience, where specific styles are applied to small screens, large screens and anywhere in between. The media query syntax allows for the creation of rules that can be applied depending on device characteristics.

<link rel="stylesheet" media="(max-width: 640px)" href="max-640px.css">
<link rel="stylesheet" media="(min-width: 640px)" href="min-640px.css">
<link rel="stylesheet" media="(orientation: portrait)" href="portrait.css">
<link rel="stylesheet" media="(orientation: landscape)" href="landscape.css">
<style>
  @media (min-width: 500px) and (max-width: 600px) {
    h1 {
      color: blue;
    }
  }
</style>

Obsolete:

@media all and ...
@media only screen and ...

Example (resize browser window to test).

Typical use is to have a container div stop increasing in width on large screens:

HTML:
<div id=container>
  ...
</div>
CSS:
#container {
    margin: 0 auto; //center on page
    width: 100%; //full width
}

@media (min-width: 960px) { //for screen widths of 960px and over;
    #container {
        width: 960px;
    }
}

The container div is centered on the page with 100% width.  Once the browser window reaches a width of 960px or more, the container div will no longer use the full width; instead, the body background will now become visible on the left and right side.

Media Queries was last modified: May 26th, 2015 by tabcom