With the mobile web comes a new set of design problems: how do you fit your content on a much smaller screen, and, more generally, how do you make your site look good no matter what size screen it’s on? The growing consensus is that Responsive Web Design — websites that adapt to the size of the user’s screen — is the way forward.
For many developers that means using @media queries to selectively target the device screen size and orientation through CSS.
While the @media approach is a good one, it won’t work for every site. That’s why Nathan Smith, creator of the 960 Grid System, has released Adapt.js, a lightweight JavaScript library (894 bytes minified) that allows you to specify a list of stylesheets and the screen sizes for which they should be loaded. Essentially Adapt.js does the work of @media, but will work in any browser, even those that don’t understand @media.
All you need to do is include Adapt.js in your pages and then define the sizes and stylesheets to go with them. Here’s the code from Smith’s example:
var ADAPT_CONFIG = {
// Where is your CSS?
path: 'assets/css/',
// First range entry is the minimum.
// Last range entry is the maximum.
// Should have at least one "to" range.
range: [
'760px = mobile.css',
'760px to 980px = 720.css',
'980px to 1280px = 960.css',
'1280px to 1600px = 1200.css',
'1600px to 1920px = 1560.css',
'1920px = fluid.css'
]
};
While using JavaScript to load CSS might seem a bit strange, even if you use @media queries you’re still going to need some kind of polyfill (usually JavaScript-based) to handle those browsers that don’t know what to do with @media rules.
Of course Adapt.js isn’t right for every situation. Smith has a very nice take on the debate over @media, JavaScript, separate mobile websites and other options for dealing with the small screen:
As with any field in which technological methods are open for debate, there is the danger of religious fanaticism, where we each rally behind a respective technique and defend it vehemently. I would advise you to consider your audience, weigh the options, and find an approach that makes sense for that particular context.
See Also:
Browse Our Tutorials
Cheat Sheets
Color Charts
Cut & Paste Code