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 {
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:


#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 }


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.



Since jQuery broke onto the scene, which now seems like a century ago, JavaScript libraries have become ubiquitous. Even the biggest fan must admit we are reaching saturation point. That said, there is a gem of a library that every developer must add to their toolbox; this little number goes by the name Modernizr.

What’s the fuss?

Mordernizr was originated by Faruk Ateş but has since got some heavy weights on board such as Paul Irish, and Alex Sextion. Based on the principles of progressive enhancement and graceful degradation, Modernizr detects browser support for the latest web technologies specifically HTML5 and CSS3 features including opacity, canvas, box shadow, svg, HTML5 input types, local and webStorage, geolocation and much, much more. This aids the developer in enhancing their web applications by providing useful information on support of a given web technology without resorting to the generally bad practice of user-agent(UA) sniffing. Conversely, if a certain feature is not supported, Modernizr will enable the developer to target a particular browser by providing a ‘hook’ in the DOM.

So how does it work?

Modernizr adds a CSS class to the root of the htmlelement of your document. So for example if I were working with canvas, it would add a canvas class where this technology is supported and no-canvas where it isn’t. I can then deal with both scenarios accordingly.

Saying that Modernizr is just a feature detection library is however selling it short. It can also be used to conditionally load scripts, build custom tests, and test media queries as I will demonstrate later. In the meantime here is a quick illustration of what Modernizr brings to the table.

Applying canvas using feature detection

No, that is not an image. In the trivial example above, we test for canvas support in the host browser before creating a canvas element and drawing a simple line. If you view this page in a browser that does not support canvas, you will get a friendly message encouraging you to upgrade your browser. In a real application, you might opt for a polyfill as a fallback solution for non-supporting browsers.

So how do I use it?

Modernizr is easy to use.

Step 1: Get a copy of Modernizr

Head off to and grab yourself a copy of the latest version of the Modernizr. You can download the full copy of the library, but chances are you only need a ‘diet’ version. In which case, the site provides a very handy tool that allows you to customize your download.

Step 2: Add to page

Script in hand, lets create a regular html document and add the Modernizr script to the page as we would any other script. Also add a ‘no-js‘ class to the html element. This will be replaced with ‘js‘ if Modernizr is running, but its also a cue to cases where JavaScript is not running and allows you to handle this scenario appropriately.

Link to script

<!DOCTYPE html>
<html class="no-js">
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
   <meta name="viewport" content="width=device-width,initial-scale=1">
   <script src="js/mordernizr.js"></script>
   <title>Do you support flexbox</title>
   <h1>Flexbox support</h1>

Voilà! We are good to go. A quick glance at DOM, we see a array of classes added to the html element and the ‘no-js‘ class replaced with ‘js‘. Of course if we only want to test support for a handful of properties/features then provides a tool for configuring your download.

Step 3: have fun

As of writing, canvas is not supported cross-browser so it makes a very good candidate. I will demonstrate both the CSS and JavaScript approaches.

CSS approach

.canvas #square{ 
  /*-- styles for #square element in browser with canvas suppport --*/ 
.no-convas #square{ 
  /*-- styles for #square element in browser with no canvas support --*/ 

In the above snippet, .canvas and .no-canvas CSS rules target element #square for canvas and non-canvas supporting browsers respectively. These classes are dynamically appended to the html element by Modernizr.

In the JavaScript variant, all the classes are properties of the Modernizr object making it easy to test for feature/property support.

JavaScript approach

var el = $('#square'); 
    //Set the background color based on canvas support
    Modernizr.canvas ? el.css({'backgroundColor':'#f0f'}) : el.css('backgroundColor':'#ccc'); 

Note: Modernizr.canvas or any other property on the Modernizr object returns a boolean (true or false). And there you have it. But we are not done yet, there is more.

Load scripts conditionally

Within Modernizr, is a small library called YepNope. This is fundamentally a resource loader that facilitates conditional loading of both JavaScript and CSS files. For example, if we wanted to load FlashCanvas (canvas polyfill) for browsers that do not support canvas, we would use Modernizr as follows:



YepNope will load files asynchronously or in parallel which will make our applications perform better. Be sure to read more about Modernizr.load() as it has more tricks under its sleeve. Some of the useful properties include;

  • load: loads a script or file and,
  • complete: a callback function. Analogous to success in Ajax

Testing media queries

Modernizr provides a neat way of testing media queries using JavaScript. Say hello to This little bad boy takes a media query as an argument and will return a boolean. For example, if we want to improve user experience on a small device by removing certain page elements from small screens, we can do the following;

if("screen and (max-width:480px)")){
  //remove secondary navigation from small screens


I hope I have managed to whet your appetite enough for you to give Modernizr a try. The library brings a lot to the table and I am sure you will at some point in your projects find it very useful. That said, tread carefully while using it especially when writing CSS. Think of a scenario where the user has turned off JavaScript (yes, people still do), or if the script does not load for one reason or another.

Useful resources

Native HTML5 datepickers with a JavaScript fallback

HTML5 Datepicker

We’ve all seen them around the web. Focus in a date input field, and a calendar datepicker pops up allowing the user to select a date. Until the advent of HTML5 and jQuery UI, developers achieved this rather mean feat by way of manipulating table cells courtesy of JavaScript. Soon enough all modern browsers will natively support calendar datepickers. As a developer all you need to do is add type=”date” to your input field and watch the browser do its magic.

Unfortunately, not all browsers at the time of writing (AHEM, no name calling) support this attribute value. I will therefore make an attempt at saving the world by demonstrating how to implement a datepicker in your form fields (you can not say I did not try) while providing a JavaScript fallback for the those browsers that are yet to implement this attribute value.


<!DOCTYPE html> 
   <title>HTML5 datepicker</title> 
   <form action=""> 
      <input type="date" name="date"> 

In the HTML markup above, we have a simple input field with type=”date”. date is one of an array of new form input attribute values in the HTML5 specification. Try this out in Chrome, Firefox and Opera, and you get a calendar datepicker when the input field is in focus. This is however not the case for Internet Explorer 9 and below.

Show some mobile device love

Mobile browsers, native or otherwise, support most if not all the new HTML5 form input attribute values. This enhances the user experience as the on-demand virtual keyboard provided is appropriate to the input field in focus. So for example; if the input field has type=”email”, you are presented with a keyboard with symbols associated to email addresses e.g @ and the top level domain(.com) in some cases. But I digress, the whole chapter of HTML5 form input attributes warrants its own forum (watch this space).

In our case, the user is presented with a calendar datepicker. The image below is a screen grab from Chrome on a Android device. Splendid indeed eh?
Chrome for Android datepicker

Fallback – Hello IE and such!(Not so much love)

The beauty of the new HTML5 elements and attribute values is that if they are not supported by the browser, they fail silently or defaults are used. In our case, IE just treats it as if it were a text input (type=”text”). However since we do not want to be sued by our friends that refuse to update their browsers or choose to use Internet Explorer, we should strive to offer a similar user experience where humanly possible or degrade gracefully. JavaScript to the rescue. Below is the revised HTML code.

Revised HTML

<!DOCTYPE html>
   <title>HTML5 datepicker</title>
   <link rel="stylesheet" href="css/ui-lightness/jquery-ui-1.8.23.custon.css">
   <form action="">
      <input type="date" name="date">
<script src="js/jquery-1.8.1.min.js"></script>
<script src="js/jquery-ui.js"></script>

//call the datepicker method on the date input field

jQuery has a user interface library with several ready-to-use plugins/widgets that are easy to implement and make adding common features such as tabs and accordions a breeze. It so happens that the UI includes a calendar datepicker widget that we can use in this case. To add the widget to your web application, stop over at jQuery UI where you will find a demo and documentation. jQuery provides an assortment of themes and you are bound to find one that suits your project.

Once you have decided on a theme, download the library. Be sure to customise your download by deselecting all first, then only adding core jQuery and the datepicker widget as you do not need the entire UI library. Do not forget to choose a theme before you click the download button otherwise your color picker will not have the CSS to your theme of choice.

As you may have noted in the revised HTML code above, I have added the jQuery UI script which has a dependency on jQuery core. I have also added the CSS that will give our datepicker the preferred theme/styling. You are now ready to apply the functionality to your input field.

Now simply call the datepicker method on the #date input field as demonstrated in the code above. You should obviously do this ‘unobstrusively’ by creating an external file, but for expedience and conciseness I have added the code at the bottom of the HTML file. And there it is folks, easy as pie, we have a cross browser datepicker. Yes, it works in IE too. Who knew?

There is however one problem, if you try out our new input field in a browser that supports this feature natively, you will notice that we are getting both the native and the jQuery plugin fallback solution, which is obviously not elegant. To solve this problem, we can add simple feature detection to our code to test weather the browser supports the date attribute value or not.

In the snippet below, we create an element and assign date to the type attribute, if the browser does not understand this value, it coerces the value to text. We then test whether our #date input type is text, if so, only then should we add the fallback. See code below and check out the demo;

Feature detection

   var el = document.createElement('input');
   //if type is text then and only then should you call the fallback
   if(el.type === 'text'){


The datepicker method can take an object as a parameter with an array of properties such as dateFormat, autoSize, minDate, maxDate that you can pass to customize the behaviour. For a definitive list, visit the demo URL above and click on options. For instance to set the date format, you would pass dateFormat:’dd-mm-yy’ as shown below

Change date format


To wrap it up, I would recommend another very nice calendar plugin that I have used in the past by Andy Croxall of the fame. Feel free to give it a try.

That’s a wrap.

CSS3 Flexible Box model

CSS3 Flexible Box modelAsk any front-end developer what they have in their armoury for laying out pages, and you are sure to get the following 3 musketeers: float, margin, and position. But move over boys, there is a new Sheriff in town and he goes by the name Flexbox.

As CSS moves into its third iteration, a range of new cutting edge toolsets have been proposed to the World Wide Web consortium w3c. Amongst these modules is The Flexible Box Layout.

What is Flexbox?

Flexbox gives elements fluidity which in turn allows them to change position in relation to their siblings or parents. This means you do not have to explicitly specify position or carry out complex calculations to for instance; center an element vertically and horizontally inside its parent. The eagle eyed amongst you can see the immediate advantages of this model.

At the time of this writing, there is a plethora of devices on which people view web pages. Consequently, it is fast becoming difficult to build pages that render appropriately to the wide and ever growing range of screen sizes and devices. Flexbox gives your designs the flexibility and fluidity needed for modern web pages to adjust accordingly.

Applying Flexbox

Applying Flexbox to a given element requires that you specify a parent or child within it. For example if you have a paragraph nested in a div, you have to give the display property of the div a value of box. This is a new value for the display property in CSS3

Applying Flexbox:

elem { display:box }

Setting this declaration on an element renders all its immediate child elements subject to Flexbox. Remember this is still a recommendation and must be used with the various vendor prefixes. i.e -moz-box, -ms-box and -webkit-box.

Practical illustration


<!DOCTYPE html>
   <title>Flexible Box layout</title>
   <h3>Flexbox model</h3>
   <div id="container">
     <div class="flex"></div>
     <div class="flex"></div>
     <div class="flex"></div>

In the contrived HTML markup above, I have three DIVS (class =’flex’) that are nested in a DIV (id=’container’). And now the CSS


  #container { display:box; width:450px; background:#c0ffee; }
  .flex { width:150px; height:150px; border:1px solid #f0f }

Running the above code in Chrome, Firefox or Opera (remember to add the respective vendor prefixes) will align the DIVS with class flex next to each other horizontally (more about IE later). For the impatient amongst you, check out the Flexible Box model demo. Note that we don’t have any floats or position rules in sight. You will however notice that the three DIVs overlap the parent and this is because the combined width including the margins and borders, exceed the width of parent. Despair not fellow developer because Flexbox Model provides a range of properties for this and many other issues that have proved rather tricky up to now.

To fix the overflow issue, the Flexbox spec provides box-flex which takes a number for a value. The value will act as the ratio to which the child elements are resized dynamically to fit inside the parent i.e if the combined values are greater than the parent and in cases where the values are less than the parent. So in our case, we will modify the CSS by adding this property to the child elements as shown below:


  #container { display:box; width:450px; background:#c0ffee; }
  .flex { box-flex:1; width:150px; height:150px; border:1px solid #f0f }

By setting the box-flex property, you trigger them to be flexible. This property is at the heart of the Flexible Box Model module. Until now, we’ve achieved this by making adding the combined values of border, padding, margin and then deducting them from the parent width, and then dividing the remainder by 3 in our case.

The box-flex property can take any value 0 or greater. Say for example, you want the second div wider than the other 2 (this is typical in layouts where you have two sidebars either side of the main content box), you would assign the second box a flex-box value greater than 1. This value represents the ratio by which the second box should be greater than the other two.

As I alluded to earlier, the Flexbox spec comes with a handful of properties that allow us to achieve tasks that up to now have proved problematic. I will not go into details about each and every one of them, but rather itemise and briefly state use of a few that you will find handy in your day to day projects.

  • elm { box-flex-group: value } : takes a number and creates groups that can be resized together.
  • elm { box-orient : value } : takes either vertical or horizontal values. This property allows you to specify how the elements should be resized. Passing vertical will resize the elements to fill the parents height and horizontal will have to opposite effect.
  • elm { box-direction : value } : the value can be either normal or reverse. This allows you to set the order of elements without resorting to JavaScript. Normal is self explanatory, while reverse sets the order of the elements in the opposite direction to how they are placed in the DOM.
  • elm { box-align : value } : values accepted are start, center or end. This property allows you to align the elements top, center and bottom respectively within the parent. I don’t know about you but, having to vertically center elements has always been tricky business for me and this property makes it a breeze.
  • elm { box-pack : value } : takes justify or center. Justify will align the first child of an element to the beginning and the last child to the end leaving any extra space between them in the middle. center will place the element in the center of its parent and distribute the extra space horizontally on either side. Combining box-pack and box-orient gives you a vertically and horizontally centered element without specifying heights and or calculating margins.

Implementation across browsers

Internet Explorer has built a reputation of coming fashionably (or NOT depending on who you ask) late to the party. Not to disappoint, Microsoft have done it again. The Flexible Box Model is implemented to a certain degree in all browsers (be it with vendor prefixes) bar IE9 and below.

That said, the implementation of the Flexible Box Module is still inconsistent across browsers and has a working draft status. See table below provided by This however should not deter you from using some of the properties be it judiciously.

Flexible Box model support
Thanks to a clever script called flexie, you can get this module to work consistently across all browsers. This script will detect whether the browser natively supports Flexbox, and if not simulate the properties. To get this script to work is super easy. Just call the script in the head section as you would any other script and be sure to add the nonprefixed properties in your CSS. e.g

Flexie CSS

elem { 
  -webkit-box-orient : horizontal; 
  -moz-box-orient : horizontal; 
  -ms-box-orient : horizontal; 
  box-orient : horizontal 


The Flexible Box Model looks to move all of us forward from the not so elegant use of floats, margins and position to layout our pages. This module is currently a recommendation by the W3C and is not definitively bound to become a candidate. That said, if all the browsers implement it then weather it becomes a candidate or not is to a degree immaterial.

At the time of this writing, implementation still looks patchy but with time this will become the standard, so you might as well get your hands dirty now, so to speak. See demo

Useful resources