Web Platform CSS

Media queries

Media queries allow you to change what rules are used depending on the characteristics of the viewer, often used for making "responsive" design.

For example, you can hide parts of the navigation when the user prints your HTML document, or rearrange elements when the browser's width gets reduced.

There are a few ways of using them, we'll just show some simple examples. To get inspired, check out Mediaqueri.es.

Print

You can specify a block of rules which only apply when the document is printed:

@media print {
  nav {
    display: none;
  }
}

There are other kinds of device you can specify besides print, including: screen, handheld, projection, screen, tv, even braille and aural. If you want to include all devices, use all.

Size-dependent

Here we declare blocks of rules which are dependent on a minimum width of the viewport. If you use these rules and change the size of your browser, you'll see the colour of the BODY element changing.

body {
  background-color: white;
}

@media all and (min-width: 200px) {
  body {
    background-color: red;
  }
}

@media all and (min-width: 800px) {
  body {
    background-color: blue;
  }
}

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

You can make more complicated media queries. For example, the following set will only be activated if the browser width is between 800-900px.

body {
  background-color: white;
}
@media all and (max-width: 900px) and (min-width: 800px) {
  body {
    background-color: green;
  }
}

You can also use: min-width, max-width, min-height, max-height, min-device-height, max-device-height.

If you care more about whether the screen is in portrait or landscape orientation:

@media (orientation:portrait) {
  body {
    background-color: pink;
  }
}
@media (orientation:landscape) {
  body {
    background-color: yellow;
  }
}

Read more