Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > CSS

  • Print
  • + Share This
From the author of Media Query Syntax Basics

Media Query Syntax Basics

Media queries extend the capabilities offered by media types—rather than just applying styles based on the medium, a media query can apply styles based on the medium plus properties of that medium. For example, you would insert something like the following into your stylesheet:

@media screen and (max-width: 480px) {
      #nav {
            float: none;
      }
   ...insert other CSS rules here
}

A media query consists of a test, followed by as many CSS rules as you want, with the rule block enclosed in a set of braces. The test in the example above says this: "If the media type is screen and if the width of the browser window is 480 pixels or less, apply the CSS rules inside the braces." If either of the test conditions is false, or both are false, the browser simply ignores the rule block and moves on.

In the syntax, you can vary the media type to any of the common types you'll use; for example, screen, handheld, print, projection, tv, or all.

You can also vary the media property (the stuff inside the parentheses). The following list describes the most common properties you'll use regularly:

  • width and height: These properties allow you to specify a specific size or a maximum or minimum width and/or height of the browser window, using any appropriate CSS units.
  • device-width and device-height: These settings allow you to indicate a maximum, minimum, or specific width or height of the actual device screen, using any appropriate CSS units.
  • orientation: Specify portrait or landscape.
  • device-aspect-ratio: Apply rule blocks depending on the aspect ratio of the device; for example, 16/9.
  • resolution: You can specify a maximum, minimum, or specific resolution for devices to which the CSS will be applied. Values are in dpi or dpcm.

In a way, media queries are like conditional (if) statements for CSS. You can use and to chain together multiple test conditions:

@media screen and (min-width: 480px) and (max-width: 960px) { ... }

To specify that only one of the conditions needs to be true (similar to or), separate the conditions with commas:

@media screen and (max-width: 760px), tv and (max-width: 1200px) { ... }

You can apply entire stylesheets selectively by putting a media query inside a media attribute:

<link rel="stylesheet" media="print and (width: 210cm)" href="a4_print_styles.css" />
  • + Share This
  • 🔖 Save To Your Account