Media Queries serve the purpose of expanding the functionality of CSS2 media types. In the past, CSS2 media types were predefined and not very flexible, some examples of these types are screen and print.

With new CSS3 Media Queries your css document can specify css rules based on variables specific to the user’s device.

The @media selector

Like the Media Type, the basis of all Media Queries in CSS3 is the @media attribute.

Example of previous usage of the @media attribute:

These worked well, but they lack the flexibility needed for today’s wide array of screen sizes.

Modern usage of CSS3 Media Queries:

In the above example we are making our body element’s background color gray. This rule only appears when the browser window’s width is equal to or greater than 768px. So if you viewed our site on an iPad the background would be gray. If you viewed it on an iPhone or desktop, it would be white. The media type all selects every media type available.

If we wanted this rule to exclusively style handheld media types:

Types

While HTML4 had set types of media which are still valid: aural, braille, handheld, print, projection, screen, tty, and tv. HTML5 doesn’t have a set amount of media types, and new ones can be created as needed.

The syntax for using types is as follows:

Dimensions

You can use height and width to query the dimensions of the current browser. You can use a min or max prefix on these dimensions which allows for more flexibility for your queries.

You can also use device-width and device-height which specifies the screen size of the user’s device. Min and max are also available as prefixes on these dimensions.

Orientation

On handheld devices it’s popular practice to query the orientation of the user’s device like so:

You can also obviously use (orientation: landscape).

Aspect Ratio

You may need to find the aspect ratio in your query:

These are only the basic ways to use CSS3 Media Queries. If you would like to see more, check out the spec on W3.org.