Responsive design – a simpler approach

If you’ve spent a bit of time working on responsive websites, you’ll have hit two problems or frustrations …

1. Scrolling up and down your css file comparing values between media query sections
2. Using mediaListeners, or checking body width just to work out what media query / display mode your page is currently using.

Inspired by libraries like moderniser or templates like html5 boilerplate that places classes in the head or body tag, I thought it would make life easier if you could place a class on an element (usually the body tag but any element is supported) and then go forth and style and code as usual.

The result is the mediaQuery plug-in for jQuery. If you want to use this plug-in you need to be comfortable with the following: you are already going to use jQuery, and you don’t mind your site being non-responsive for non-javascript users.

On the positive side, the plug-in includes polyfills for css media queries and the matchMedia and addEventListener javascript functions – so you wont need to include any other code to support responsive across all browsers.

Usage is really simple:


$('body').mediaQuery({
  w320: 'only screen and (min-width: 320px)',
  w480: 'only screen and (min-width: 480px) ',
  w768: 'only screen and (min-width: 768px)',
  w1024: 'only screen and (min-width: 1024px)'
});

This code will add the classes w320, w480, w768, w1024 to the body tag depending on each of the corresponding media queries matching.

Your css is then as simple as this eg:


.w320 .content p {
  background-color:#d45354;
}

.w480 .content p {
font-size:3em;
width:360px;
height:360px;
line-height:360px;
background-color:#818b85;
}

Checking for different media queries is now as simple as this line of jQuery code:


if ($(element).hasClass('w1024')) ...

You can view an example of the technique here: http://jameswestgate.github.com/mediaQuery/examples/

Advertisements
Responsive design – a simpler approach