CSS Media Queries

A @media query returns data about the device the page displays on.

This includes device type, dimensions, resolution, orientation, and more.

This data helps with creating an optimal user experience for each device.

Media queries are key to building responsive web solutions.

Example

#

In this example, the style changes with the device width.
Resize the browser to see the background change at multiple stages.

Resize the browser and see the background change
<style>
  .my-style {
    background-color: aliceblue;
    padding: 30px;
  }

  @media (min-width: 254px) {
    .my-style {
      background-color: greenyellow;
    }
  }

  @media (min-width: 456px) {
    .my-style {
      background-color: lightyellow;
    }
  }

  @media (min-width: 576px) {
    .my-style {
      background-color: lavenderblush;
    }
  }

  @media (min-width: 768px) {
    .my-style {
      background-color: honeydew;
    }
  }

  @media (min-width: 992px) {
    .my-style {
      background-color: cornsilk;
    }
  }

  @media (min-width: 1200px) {
    .my-style {
      background-color: aliceblue;
    }
  }
</style>

<div class="my-style">
  Resize the browser and see 
  the background change
</div>

Using Media Queries

Media queries were introduced in CSS3.

Not only do they detect the device type, but also the device capabilities.

Media queries check for these characteristics:

  • device type: screen, print, speech, or all.
  • width and height of the viewport
  • width and height of the device
  • orientation: landscape or portrait
  • screen resolution
  • color depth

Syntax

Syntax for media queries.

@media not|only mediatype and (expressions) {
  CSSCode;
}

mediatype -- can have any of these values:

  • all -- all media type devices. default.
  • print -- printers
  • screen -- computer screens, tablets, smart-phones etc.
  • speech -- screenreaders that read the page out loud

expression -- a logical expression with media capabilities:

  • min-width
  • max-width
  • min-height
  • max-height
  • orientation
  • resolution
  • color, monochrome
  • aspect-ratio
  • hover
  • and more...

Logical expressions can include and, only, and not.

Expression also support operators like >=, <, ==, !=, and more.

If the query returns true the CSS style takes effect.

Media queries are used also by HTML elements with a media attribute. These include <link>, <style>, <source>, and others. Below is an example.

<link rel="stylesheet" 
      media="mediatype and|not|only (expressions)"
      href="style.css">

Browser Support for Media Queries

For each browser see which version and on what date support started for the CSS media queries.

Chrome
21.0 Jul 2012
Firefox
3.5 Jun 2009
IE/Edge
9.0 Mar 2011
Opera
9.0 Jun 2006
Safari
4.0 Jun 2009

You may also like

Guides