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:

$('div.container').classBySize({
    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.

5 Comments

  • 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.

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

  • Ever checked out css media queries?

  • 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.

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

Leave a Reply

Your email is never shared.Required fields are marked *