Media Queries and responsive web design

Media Queries

Try viewing my site on a small device or resize your browser window, and you will notice that the page content ‘responds’ to the size of the viewport by readjusting the layout. How did you do that? you might ask. Well, I will tell you and no, I won’t have to kill you. Say hello to a fairly new paradigm that is responsive web design courtesy of Media Queries.

What are Media Queries?

As can be deduced from the name, Media Queries are a means of targeting media types by way of their characteristic features. So for example; you can define a media type e.g screen or projection and then specify a width, height, orientation or color. This gives us as developers a lot of leverage and enables us to easily and quickly optimise our web applications with minimal extra development and without resorting to ‘browser sniffing’.

Let me demonstrate.

Media queries demo

@media screen and (max-width:600px){
  #med-q-demo {
    background:#FE57A1;
  }
}
This box will turn hot pink if browser window is less than 600px

In the very trivial example above, when the browser viewport is less than 600px (including the scroll bar), the media query fires the encapsulated CSS. It doesn’t take a lot of imagination to see the power put to our disposal. Go on, you know you want to see that hot pink background; resize your browser or view this page on a small screen device.

Syntax and declaration

Media queries are declared the same way CSS is applied but can be used with JavaScript as well.

Method 1

Add a link element in the head section of your document to call an external stylesheet:
<link rel=”stylesheet” media=”only screen and (max-width:480px)” href=”small_screens.css” />
A BEST PRACTICE: Create a basic stylesheet for your mobile users first, then one for tablets and desktop users. Taking this approach means, you avoid loading large assets which affect load speeds and are bandwidth intensive on mobile devices. Then use Media Queries to load the appropriate stylesheet. I can hear you saying; but there is no support for Media Queries in IE8 and below! We can get around this by using conditional comments. This is a mobile first approach which is advocated by a growing number of web developers.

Method 2

Call an external stylesheet inside another stylesheet using the @import directive:
@import url(‘small_screens.css’) only screen and (max-width:480px)
This is however considered an anti-pattern as the rest of your CSS will stop loading while the @import file loads, which might result in the user momentarily viewing the un-styled version of your page.

Method 3

Embed the Media Queries in your stylesheet using the @media rule:
@media only screen and (max-width:480px){ /*– your CSS rules –*/ }
In cases where the application does not warrant a separate Media Queries stylesheet, you can add your query within your normal stylesheet.

Method 4

We can also use JavaScript to work with Media Queries by tapping into window.matchMedia which returns a mediaQueryList object. This object has two properties:
matches: returns a boolean on a query.
media: serialised media query list.
Here is the syntax:
var smartPhones = window.mediaMatch(‘(max-width:480px)’).matches
The simple code above will return true if the viewport size is 480px or less.

NOTE: we use the only value to hide the rule from old browsers that do not support the syntax. This is ignored by browsers that support Media Queries. We can also use not to negate the Media Query.

Media features

Media features constitute any information about the host medium e.g width, height, orientation, pixel-ratio, and pixel-ratio. Most features require a value in the expression part of the Media Query which takes the following syntactical form:
@media media and (feature:value) { CSS rules } Note that this does not always have to be the case. For instance you could just test for the presence of the feature; @media media and (feature){ CSS rules }

Width and Height

width and height refer to the width and height respectively of the rendering viewport including scroll bars on desktops. These two features can be prefixed with min- and max- as the non-prefixed variants will in most cases be too specific. A practical example would be if you wanted to add a background image for browser windows over a certain width, you would do something like this:

min-width in action

@media screen and (min-width:500px){
  body { background-image: url(bg_img.png) repeat-x;  }
}

The Media Query in the above snippet tests for browser windows that are atleast 500px to apply the background image. In real world applications it’s recommended to limit the number images loaded on smartphones and tablets as they affect page load speeds and users’ bandwidth. The above technique lends itself to this. You could also use other techniques such as responsive images.

Device-width and height

This works exactly the same as the preceding example except the width is a reference to the device on which content is rendered as opposed to the browser window. As with the width feature above, device-width can be prefixed with min- and max-. This is especially useful for targeting smartphones and tablets. Let me demonstrate:

device-width

#wrapper { width:600px; }
 #wrapper div { float:left; width:290px; margin:0 10px 0 0; }
 @media screen and (max-device-width:320px){
  #wrapper { width:auto; } 
  #wrapper div { float:none; width:auto; margin:0; }
 }

In the code above, we have a wrapper div with a fixed width that contains two divs with explicit widths. This is fine for desktops but is not ideal on small devices e.g iPhones because screen real estate comes at a premium. To solve this, we use a Media Query that tests for devices with a maximum width of 320px (iPhones fall in this category), and we apply rules to remove the floats and explicit width which forces our divs to stack. View demo.

I am not going to go into details about all the Media Features but here is a list of some and what they do:

  • Orientation : used to optimise pages based on whether the device is in a horizontal orientation (width greater than height) or vertical orientation (height greater than width). @media media and (orientation:value) { CSS rules } This Media Feature is best suited for controlling content display on handheld devices.
  • Aspect ratio : Tests width-to-height ratio@media media and (aspect-ratio:ratio) { CSS rules }

Multiples

You can test for more than one Media feature on a media type. Take an example where you wanted to test for tablets in a horizontal orientation. This is the syntax:
@media only screen and (min-device-width:768px) and (max-device-width:1024px) and (orientation:horizontal) { CSS rules }

In a nutshell

Building responsive web applications is undoubtedly the future of web development. More people than ever before are viewing content on the go thanks to ever faster network speeds on tablets and smartphones. It is on this premise that as web developers we must move away from the mindset of building applications that only target a given resolution.

The Media Queries module has Candidate Recommendation status and therefore considered ready for implementation.

5 thoughts on “Media Queries and responsive web design

  1. Thanks for the feedback. I know the ‘mobile-first’ approach is a tud contentious but hey, that’s the beauty of web dev.

  2. Nice blog post Samson. As you know, I am no web developer but I do know how to market online, test sites and what are good for users and mobile responsive sites are a great addition to the web world. Google is also ‘hinting’ that it would be ‘nice’ if you have a mobile responsive site, not just an alternative mobile site on a slightly different URL.
    I give my clients the option of all and would advise most to now have mobile responsive.
    You need to get this message out further mate… :-)

    • Thanks Del. With regards to pushing the message, you are the man with the midas touch so do your magic.

Leave a Reply

Your email address will not be published. Required fields are marked *