Screen size dependent CSS with jQuery

A simple jQuery plugin to let the CSS handle resolution dependent content – jQuery.classBySize(). This little plugin maps the current document’s size to classnames applied to the element the plugin is used on.

For example:

    0: 'without-side without-header',
    600: 'without-side',
    900: ''

Would add a without-side without-header class to the div.container element, whenever the size of the document is between 0 and 600. If between 600 and 900, the without-side class is added. If more than 900, all classes are removed. The classes are mutually exclusive; that is, all classes of all sizes are removed before the applicable size class is added. That’s why in this example the without-side class is mentioned in both the 0 and 600 size.

The advantage of using a plugin for this, rather than showing or hiding all kinds of elements based on events, is that the entire display is controlled from the CSS.

This entry was posted in Development and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. sybolt
    Posted December 7, 2010 at 20:50 | Permalink

    Would be nice if you can also do things like this server side. e.g. Maps screen resolution/viewport size to image-cache-presets for drupal. So mobile viewers don’t have to download the high resolution images but get the smaller ones instead.

  2. Posted December 7, 2010 at 21:22 | Permalink

    Who needs drupal with image cache if you also could use nginx with image filter

  3. Paul
    Posted December 8, 2010 at 07:40 | Permalink

    Ever checked out css media queries?

  4. Posted December 8, 2010 at 09:50 | Permalink

    Looks nice and handy, but it only works for ths x-axis. It might be handy to implement both axes, like: $('div.container').classBySize({ x: { 0: 'without-side without-header', 600: 'without-side', 900: '' }, y: { 0: 'without-footer without-header', 300: 'without-footer', 500: '' } });

    Also, I would use the numbers as max size before classes will apply. This seems more logical, since you’re usually hiding items when document size is below a certain value. This way you could also omit the last ” value, which is needed now.

  5. drm
    Posted December 9, 2010 at 08:45 | Permalink

    Based on several comments, discussions and some thoughts I’ll make some changes soon.

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Subscribe without commenting