Techniques For Gracefully Degrading Media Queries

Advertisement

Media queries are the third pillar in Ethan Marcotte’s implementation of responsive design1. Without media queries, fluid layouts would struggle to adapt to the array of screen sizes on the hundreds of devices out there. Fluid layouts can appear cramped and unreadable on small mobile devices and too large and chunky on big widescreen displays. Media queries enable us to adapt typography to the size2 and resolution3 of the user’s device, making it a powerful tool for crafting the perfect reading experience.

CSS3 media queries, which include the browser width variable4, are supported by most modern Web browsers. Mobile and desktop browsers that lack support will present a subpar experience to the user unless we step up and take action. I’ll outline some of techniques that developers can follow to address this problem.

screenshot

It Depends

If you’re looking for the more honest, truthful answer to pretty much any question on web design and usability, here it is: It depends.

Jeremy Keith5

There is no one-size-fits-all fix. Each project has its own focus, requirements and audience. This article will hopefully help you make the best decision for your project by outlining the advantages and disadvantages of each solution.

Mobile First

Your chosen implementation of media queries will have a big effect on how you tackle this. Mobile-first responsive design is the process of building a mobile layout first, and then progressively modifying the layout as more screen space becomes available. This ensures that only the minimum required files are loaded, and it keeps the mobile solution lightweight. Mobile first has the advantage of providing a nice fallback for mobile devices that don’t support media queries, such as older BlackBerrys, Opera Mini and Windows Mobile devices. These devices simply see the most basic layout, with no extra work required of the developer. Ideal!

Technique 1: Do Nothing

Sometimes the lazy approach is the best approach. It keeps your code light and maintainable and reduces any needless processing on the client side. Some old browsers run Javascript like a dog, and old mobile phones struggle to run intensive Javascript. The proprietary non-Webkit browser in most BlackBerrys can take up to eight seconds6 just to parse the jQuery library. If your project has a long tail of users with low-powered mobile devices, then maybe a mobile-first approach is enough for you.

The elephant in the room is Internet Explorer for the desktop. With a mobile-first solution, large screens will display the content in one column, resulting in a painful reading experience for the user, way past the established maximum for comfort: 50 to 75 characters.7 It might be worth setting a max-width property in your main container and then upping that max-width in a media query.

#container {
 _width: 460px; /* Take that, IE6! */
 max-width: 460px;
}

@media only screen and (width) { /* A quick and simple test for CSS3 media query support. */

#container {
  max-width: 1200px; /* Add the real maximum width here. */
 }

}

Do Nothing If…

  • Your core audience uses modern smartphones,
  • You are required to provide an acceptable experience to a long tail of feature-phone users,
  • The desktop is not a big part of your Web strategy.

Example: jQuery Mobile8 (“Any device that doesn’t support media queries will receive the basic C-grade experience”).

Technique 2: Conditional IE Style Sheets

Surprisingly, in researching this article, I found this to be the most popular technique in use on responsive websites. Instead of polyfilling support for media queries, you simply you simply load an additional style sheet only for Internet Explorer load the same stylesheet that you’re serving up to browsers that do understand media queries for Internet Explorer. For mobile-first approaches, this usually entails loading a basic style sheet that sets up a multi-column layout for large screens. Jeremy Keith documents this approach9 in detail on his blog. He also adds a condition that doesn’t load the style sheet for mobile versions of IE. Crafty.

It’s a simple and effective technique for supporting Internet Explorer on the desktop, and it supports the mobile-first approach because it loads a light and appropriate linear layout for feature phones.

On the other hand, this technique could potentially degrade maintainability, requiring you to maintain a style sheet of duplicate content. It also adds another HTTP request for IE users, which should be avoided if possible.

I’m surprised that Jeremy Keith advocates this technique. The man who proclaimed on stage that user-agent sniffing is “the spawn of Satan10” is using a solution aimed squarely at one browser. Bear in mind that this does not work with browsers that do not support CSS3 media queries. But it can be perfectly acceptable in situations where support for other legacy browsers is not required.

Use Conditional IE Comments If…

  • You are using a mobile-first workflow;
  • Your media queries are simple enough to include in a single style sheet;
  • Desktop Internet Explorer requires a multi-column layout, at the expense of speed;
  • You do not have to support a long tail of legacy desktop browsers.

Example: Huffduffer11, a mobile-first approach with an additional column for screen widths over 480 pixels.

Bonus example: Designing With Data12 by Five Simple Steps. I love these guys.

Technique 3: Circumvent Media Query Conditions

The Opera Developer Blog published an article in 200713 detailing the safe usage of media queries. It helped pave the way for CSS3 media query usage by presenting research on the correct way to write them, a way that prevents browsers from applying the containing CSS when they do not understand a media query.

… Browsers like IE.

But what if, with a mobile-first approach, that’s exactly what we do want? What if we were to write our media queries so that the containing CSS gets applied by IE unconditionally. We could then have our full desktop layout without any additional style sheets to load or maintain.

@media screen, all and (min-width: 300px) {
	div {
		background: blue;
	}
}

As the blog post states:

Now it is no longer the case that IE does not apply the contents of the query. It now doesn’t understand the second part (all and), so it ignores that and happily applies the contents of the query…

Circumvent Media Query Conditions If…

  • You are only required to support modern smartphones,
  • You are building mobile first and require a desktop layout in IE,
  • Loading time and maintainability must be kept to a minimum.

Technique 4: Respond.js

Scott Jehl14’s lightweight polyfill Respond.js15 offers a leg up for browsers that do not support CSS3 media queries. It can be compressed down to as little as 1 KB, and it parses CSS files fast, without needing any additional libraries.

JavaScript reliance aside, Respond.js appears to be a solid solution for full support of media queries. However, the small file size and speed come at a cost. Respond.js was never meant to be a full-featured solution. Its purpose is to provide the bare minimum for responsive layouts to work.

It supports only the min-width and max-width queries, so it’s not the right solution if you are looking at using device-width, device-height, orientation, aspect-ratio, color, monochrome or resolution. Some good use cases here are not supported, one being the detection of high-resolution devices such as the iPhone 4 and non-color devices such as the Kindle.

Respond.js does not support em-based queries16, which makes impossible any decent support for font-size user preferences (even more important on a small screen than on a desktop). Products like Readability17 and Reeder18 validate this desire among users to control and refine the reading experience. Em-based media queries will become only more important as we head towards a content-first19 approach to Web design, so they are worth considering.

There are a lot of small bumps and caveats with Respond.js. I recommend browsing the read-me text20 and the issue queue21 before settling on it for you project.

Use Respond.js If…

  • Desktop support is a primary high concern,
  • You are querying only the width and height of the browser,
  • You don’t want to query the width by ems,
  • You have no problem with non-JavaScript users seeing an unoptimized page.

Example: Aaron Weyenberg22, a desktop-centric website with a basic layout.

Technique 5: CSS3-MediaQueries-js

CSS3-MediaQueries-js23 picks up where Respond.js leaves off. It supports the full range of media queries introduced in CSS3. The “everything and the kitchen sink” approach is great for a developer’s peace of mind. Simply drop it in, and tick the “IE support” box.

But there are significant downsides to consider: this script is not fast; it parses CSS much slower than Respond.js; and it weighs in at a hefty 15 KB.

Pro Tip 1

Let’s be responsible and load this file only if the browser doesn’t actually support CSS3 media queries. Otherwise, you’re wasting good time and data. You can use Yepnope24 to load the 15 KB file if it detects that media queries are not available.

Here’s a modification of a Yepnope function that I wrote for Modernizr25’s media query test. Yepnope now comes bundled with Modernizr.

yepnope({
test : Modernizr.mq('@media only screen and (width)'),
yep  : '',
nope : 'css3-mediaqueries.js',
});

If you don’t require support for non-IE devices, then replace the Yepnope function with a much lighter conditional comment.

<!--[if (lt IE 9) & (!IEMobile)]>
 <script src="css3-mediaqueries.js"></script>
 <![endif]-->

Pro Tip 2

If you are building for mobile first, then adding a min-device-width condition to the Yepnope query is definitely worthwhile. This will prevent the hefty 15 KB file from loading on small screens that will never use it. Win!

Use CSS3-MediaQueries-js If…

  • You are using advanced media queries, beyond simple pixel-width conditions;
  • You are happy to take that 15 KB loading hit;
  • Your audience doesn’t include a long tail of feature-phone users.

Example: Hicksdesign26 uses complex media queries beyond simple width and height.

In Conclusion

Responsive design is still a new way of thinking. Media Queries are a great tool to enhance the experience of browsing a web site on multiple devices and it’s a great idea to consider devices that do no support them. We would be dreaming if we expected an easy solution from day one but at least we have a range of options in front of us that allow us to find the best solution for the problem at hand.

It’s important to bear in mind that context is key, a well informed decision will always yield better results instead of quickly choosing the most popular solution.

(al)

Footnotes

  1. 1 http://www.alistapart.com/articles/responsive-web-design/
  2. 2 https://developer.mozilla.org/en/css/media_queries#device-height
  3. 3 https://developer.mozilla.org/en/css/media_queries#resolution
  4. 4 https://developer.mozilla.org/en/css/media_queries#width
  5. 5 https://twitter.com/#!/adactio
  6. 6 http://twitter.com/#!/lyzadanger/status/80785241521913856
  7. 7 http://www.webtypography.net/Rhythm_and_Proportion/Horizontal_Motion/2.1.2/
  8. 8 http://jquerymobile.com/gbs/
  9. 9 http://adactio.com/journal/4494/
  10. 10 http://adactio.com/articles/4661/
  11. 11 http://huffduffer.com/
  12. 12 http://www.designingwithdata.com/
  13. 13 http://dev.opera.com/articles/view/safe-media-queries/
  14. 14 https://twitter.com/#!/scottjehl
  15. 15 https://github.com/scottjehl/Respond
  16. 16 https://github.com/scottjehl/Respond/issues/18
  17. 17 http://www.readability.com/
  18. 18 http://reederapp.com/
  19. 19 http://adactio.com/journal/4523/
  20. 20 https://github.com/scottjehl/Respond#readme
  21. 21 https://github.com/scottjehl/Respond/issues
  22. 22 http://aaronweyenberg.com/
  23. 23 http://code.google.com/p/css3-mediaqueries-js/
  24. 24 http://yepnopejs.com/
  25. 25 http://www.modernizr.com/
  26. 26 http://hicksdesign.co.uk/

↑ Back to topShare on Twitter

Lewis Nyman is a designer and a front-end developer blogging at http://lewisnyman.co.uk/ .

Advertising
  1. 1

    Great article dude, finally some practical advice and clarity on what to do and when to do it.

    1
  2. 2

    Yep, very good round-up of the options available and when to use them. I’ve been working with #4 myself recently.

    0
  3. 3

    This is a very good article with a handfull of options. I prefer your option 5 but as you said, it always depends on your target audience.

    Thank you !

    0
  4. 4

    Great article Lewis,

    Just got one question… these days alot of peeps seem to focus on the ‘Mobile first’ principle.

    And while it’s valid in terms of being light weighed, the majority of non css3/media query enabled page views will still come from desktop environment. On top of that, effective mobile and desktop communication isn’t always presenting the same information.

    Mobile is much more getting the right information now where as desktop browsing lends itself much more for customer engagement.

    Wouldn’t an ‘outdated-first’ approach make much more sense?

    By starting off with a 768px design old desktop browsers get a nice view and you grab slates/ipad simultaneous. Then depending on budget/analytics and time you can upgrade with several broader screen formats and downscale for one or two mobile formats…

    0
    • 5

      Hey Jochem,

      Thanks for the comment, appreciate it.

      Yeah, there are situations where a ‘desktop first’ approach is the right way to go. It’s great where you are planning on quickly making a desktop centric site small screen friendly to cope with rising smartphone traffic. You can assume new user agents have support for media queries and desktop IE will simply stay the same. It’s the other side of the ‘Do Nothing’ approach.

      0
  5. 6

    Won’t technique #3 break browsers that do support media queries? Browsers that do understand media queries will apply those styles regardless of whether the viewport min-width is 300px or not.

    0
    • 7

      For those browsers that understand media queries, I imagine the “and” keyword is the magic sauce that avoids what you are proposing. In computer code, if you “and” conditionals together, all conditional statements have to be true for the evaluation to be valid. If any one condition fails, then the entire evaluation fails.

      0
  6. 8

    Hi Lewis,
    Thanks for covering Respond.js! However, there are a few corrections I’d like to suggest. Under the Use Respond.js if points:

    – “Desktop support is your primary concern”: I’m not sure I’d agree with this point, as respond.js is more geared towards mobile-first development, if anything (through mobile-friendly filesize, and support for devices such as Windows Phone 7). Could you clarify what this point means, perhaps?

    – “You are querying only the width and height of the browser”: While it’s true that min and max width queries are the only ones that respond.js will translate, you can use other queries as much as you’d like. If certain query types don’t apply in IE, it may not be a huge problem.

    A couple other minor nits: the fact that respond.js does not translate queries for pixel density shouldn’t affect too much; I’m not aware of any non-media query-supporting devices with HD/retina displays. Of course, you can still use HD/retina queries to target devices that do. Lastly, lacking support for em-based media query units should not have any effect on a user’s or developer’s ability to scale the text of the site, or set the fonts and elements in em units. This limitation is purely about using em units in the queries themselves, which is not very common anyway.

    All that said, I appreciate the mention! Thanks, Lewis.

    0
    • 9

      Hey Scott,

      Thanks for the comment, all solid points. Respond.js is a great tool to a present day situation which is why a lot of the downsides aren’t common use cases, at least not right now. Responsive design is still young and there is no reason to limit it to pixels on a screen. Ems are content sensitive, not screen sensitive.

      Repond.js is great compliment to a mobile first solution, if you are planning on scaling all the way up to desktop screen sizes then it is a great choice. Which makes desktop a *high* concern. I’ve updated the post with the correct wording.

      Please keep up the good work!

      0
      • 10

        Great article!

        FYI – The latest release of Respond.js now allows you to use ems in media queries.

        0
  7. 11

    Matthew Litherland

    August 10, 2011 6:25 am

    Great article, i’ve been looking for this kind of info for aaaages!

    0
  8. 12

    Hi Lewis,

    Good article, but there are a few inaccuracies in some of the things you’re claiming I’ve said and done.

    Regarding using conditional comments for IE, you say:

    “Instead of polyfilling support for media queries, you simply load an additional style sheet only for Internet Explorer.”

    That’s not what I’m doing. I’m loading *the same* stylesheet that I’m serving up to browsers that do understand media queries. It’s all in the blog post of mine that you linked to.

    So this statement isn’t correct:

    “this technique could potentially degrade maintainability, requiring you to maintain a style sheet of duplicate content.”

    Modern browsers and IE less than 9 (but not mobile) are sent to the *same* stylesheet. In other words, it is much more like the third technique you show (circumventing the media query for IE).

    Then you say:

    “I’m surprised that Jeremy Keith advocates this technique. The man who proclaimed on stage that user-agent sniffing is “the spawn of Satan” is using a solution aimed squarely at one browser.”

    I didn’t say that user-agent sniffing is the spawn of satan: I *asked* my panelists if it was. Again, it’s all there in the article you linked to.

    Just thought I’d better clear that up.

    Thanks for gathering these different techniques into one place.

    0
    • 13

      Jeremy, thanks for clarification. The article was updated. Sorry for any inconvenience caused.

      0
    • 14

      Hey Jeremy,

      Thanks for the clarification, very fair, the last thing I would want to do is misrepresent someones work. The article has been corrected.

      0
  9. 15

    Great article Lewis- I don’t have much to add to that other than stressing how awesome Mobile-first is. Really gets to the core of *progressive enchancement*, rather than the past hacky ways of display:none/float:none-ing elements as you work your way down the viewport size scale :)

    0
  10. 16

    Thank you for this post – it’s always handy to have clear, simple tips bookmarked for future use :)

    0
  11. 17

    This support for CSS media queries provided by third party solutions should be implemented by the W3C from the word go IMHO. Having to use one or another third party solution to circumnavigate browser/platform issue’s is just another repeat of the stupidity of CSS hacks with weak browsers (namely Internet Explorer [of course]).

    Why hasn’t the W3C thought of the features (additions) provided by the third party solutions, and implemented them into the standards? I’m all for the standards, and when will the browser vendors (namely Microsoft [of course]) actually catch up with the latest W3C requirements?

    Just feels like the web is about to fall apart (again).

    0
  12. 18

    Wow, great article and great comments in here. Still very new to this RWD stuff but getting up to speed albeit if slowly. Thanks!

    0
  13. 19

    It would worth mentioning that respond.js can be bundled up with a custom build of Modernizr see the build page http://www.modernizr.com/download/

    0
  14. 20

    It seems the simple example in technique 3 doesn’t work in IE8 (works great in IE7 though), which kinda defeats the purpose of the teqhnique, I think.

    Bummer, because otherwise it was exactly what I was looking for – a way to get older IEs to ignore the media query rules and just use the styles within.

    The search continues…

    0
    • 21

      I found this, which is basically the quest for a media query rule that IE8 ignores: http://jsfiddle.net/boblet/59e99/

      0
      • 22

        Also got very excited when I read technique 3. However, reading Aarfing’s comment and JSfiddle it looks as though IE8 struggles. I think I’ll continue with Jeremy’s solution for now. I’ve found the JS polyfills have caused problems on more complicated layouts.

        0
  15. 23

    Dear sir,
    Is it not possible for articles like your beautiful one, to be written in a way that can help learners? You have obviously targeted your work at experts like you. Less-than-experts like me benefit precious little from your important work. This also goes for your peers. You are addressing yourselves instead of people like me who most need your help. Please attempt to redo this article for the understanding of even the ‘dumb’ please.

    0
    • 24

      Hi Nedum,

      Thanks for the comment. It’s great to get feedback from a range of readers.

      This article was tricky because it’s purpose is to solve a problem at a later stage of the development process.

      I guess I could of gone in to more detail about media queries and how you use them but it felt out of the scope of something that was meant to be a concise, helpful article. I did decide to assume a working know of media queries in the article and maybe I should of added some links to ‘catch up’ on media queries in the introduction.

      Is there anything in particular you found confusing?

      0
  16. 25

    Just a head’s up that your Modernizr.mq() example no longer works (not in 2.0.6 anyway).

    You don’t include the ‘@media'; so a typical example would now just be:
    Modernizr.mq(‘only screen and (max-width: 768px)’);

    0
  17. 26

    An outstanding share! I’ve just forwarded this onto a colleague who had been conducting a little homework on this. And he actually bought me breakfast simply because I found it for him… lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending time to discuss this matter here on your internet site.

    0
  18. 27

    Stephanie Hobson

    April 20, 2012 9:56 am

    I gave technique 3 a try and was disappointed to find that all browsers I tested in were applying the rule unconditionally, not just IE. This makes sense, the rule basically says “apply this to a screen and to anything over 300px wide” but a screen under 300px wide is still a screen.

    0
    • 28

      Really?

      I tried it in a JSFiddle and it worked like a charm: http://jsfiddle.net/Baumr/9Atn6/2/

      I’m really curious to hear what’s not working! :)

      Thanks

      0
      • 29

        I’m not sure what I’m missing, but I had the same experience as Stephanie. “@media screen, all and (min-width : XXXpx)” causes all browsers to apply the rules defined inside the media query, regardless of width. You should probably remove that technique from the article.

        0
  19. 30

    bookmarked!!, I like your site!

    0
  20. 31

    Here are a couple other valid techniques, assuming you’re using a CSS preprocessor:

    http://jakearchibald.github.com/sass-ie/

    http://nicolasgallagher.com/mobile-first-css-sass-and-ie/

    We’ve been using a modification of the second (from Nicolas Gallagher) with great success.

    0
  21. 32

    The “@media only screen and (width)” hack for IE8 should be “@media only screen and (min-width: 0px) for it to work.

    0
    • 33

      @Johan what do you mean? Why 0px? Could you give a few more details on what your talking about?

      0
  22. 34

    So, is technique #3 not really valid if you want full IE6 – 8 support? Seems like this article should be updated to let people know that #3 isn’t really a solution (at least, that’s what I gather from reading the comments). What’s up?

    EDIT: I just tested using browserstack.com, and like others have stated, IE8 fails but 6 and 7 work! OMG, so close yet so far away!!!!!!! dIE dIE dIE!!!!

    0
  23. 35

    I was just wondering the scripts you mentioned in the article ( respond.js and css3-mediaqueries.js ) will only work if we are on a javascript enabled browser. Then why do we not do it with javascript only? We can check the browser’s width and them code the css with it. Is the approach appropriate or is there any downside? Do reply soon. Thanks

    0
  24. 36

    Michael Morici

    May 21, 2013 7:37 pm

    I’ve got a method that is a combo of #2 (the IE conditional) and #3 (circumventing media query conditions).

    The idea is to use a preprocessor like LESS to create an alternate version of the stylesheet where the media queries are converted into media types like `screen` or `all`. Media types are supported by IE8-6 and you would serve this modified version to IE with a conditional comment.

    So one stylesheet would use media queries as normal `@media only screen and (min-width: 600px) { … }`, and the IE stylesheet would convert the query to a type `@media all { … }`.

    I’ve documented it in more detail here: https://github.com/himedlooff/media-query-to-type

    0
  25. 37

    In most of the projects I work on I still need to support old IE versions. Most of my sites still have a significant number of visitors with IE8, and some run in compatability mode so they run as if using IE7. I try and develop in such a way that my sites work similarly on IE6 and above, as well as all the other more modern browsers.

    For responsive design I have been using JavaScript (and jQuery) as an alternative to media queries. Based on browser width on load and resize I apply and remove classes from the BODY tag. If JavaScript is disabled then the default styles are used so just misses out on the media query like styles. As much as I would love to drop support for old browsers, I can’t ignore them, so at this stage I think this is a good solution. I have some sample code on my blog (http://blog.johnavis.com/blog/default.asp?id=722) and my blog actually uses this technique.

    I also wrote about a jQuery based solution to responsive image sizing which uses server-side image sizing to load the right size image (http://blog.johnavis.com/blog/default.asp?id=723).

    Hope these techniques might be of interest.

    0
  26. 38

    I just tried circumventing media queries for IE by using method #2, but it seems that it circumvents media queries for other browsers as well, Chrome included! Maybe the rules for how to put together a proper media query have become more strict?

    0
  27. 39

    I have been researching mobile screen resolution.

    It looks like you can design for the desktop first.

    Today’s iphone, ipad, ipod resolutions are about just as good as the desktop resolutions.

    Android is almost just as good as the ios resolutions.

    It looks line responsive web design will become a thing of the past.

    0
  28. 40

    Hi Lewis! Thanks for the great post! Hope you’re well.

    Nicely degrading a mobile first website is always tricky for legacy browsers. In our case, we had problems with respond.js and CDN, causing a several delay until you saw the final site. You would see a flash of the mobile site beforehand and in general the performance was pretty poor.

    Drupal Media Query Fallback to the rescue!

    I developed a solution to parse the css upfront on the server and provide a fixed width CSS via conditional stylesheets to IE8. It is a module for Drupal which you can just turn on and set the width. It will extract all the media queries at that given point. It is compatible with Less and CDN. The great benefit of this approach is that you can stick with your mobile first approach and IE8 will gracefully degrade to a ‘normal’ breakpoint or any of your liking. All can be cached and the speed is amazing.

    Here is the module in case you are interested: https://drupal.org/sandbox/jnpwebdeveloper/2203845

    0

↑ Back to top