WordPress Code Snippets

A fresh mix of code snippets and tutorials

Notes on @media queries


Just a couple of notes for working with CSS @media queries: two ways to write media queries and how to query portrait vs. landscape orientation.

Two ways to specify media queries

Here are two acceptable ways of writing media queries:

via HTML link tag

via CSS stylesheet

Each of these examples targets any screen with a maximum width of 480px, OR any device with a maximum width of 480px. That is, the comma is equivalent to “OR” when included in media queries.

Tip: to save a few bytes when targeting all types of media you can omit the “all and” and just write (max-width: 480px), (max-device-width: 480px). That is, when the media type keyword is omitted, the default value of all will be used.

Using orientation in media queries

Here is an example demonstrating use of orientation in @media queries.

Using this HTML:

<div class="example"></div>

And this CSS:

The results will be such that:

  • In portrait orientation the <div> will be displayed at 500px width with a red background.
  • In landscape orientation the <div> will be displayed at 800px width with a transparent background.

Tip: to get a smooth transition effect on supportive browsers, you can add transition: all 1s ease; to the .example selector outside of the @media queries. That will animate the changes in width and background-color when the screen is rotated from portrait to landscape (or vice versa). Note that you may want to use vendor prefixes for transition to provide wider browser support.

Show Support

Like our new Facebook Page to show support!