Drupal and Media Queries: more control of your styles

With CSS3 the W3C has introduced a new goodie for design on the web: Media Queries. Until then stylesheets could only be called conditionally by using media types like "print" or "screen". Media Queries extends this to being able to use certain properties as a controlling mechanism if to load a style or not.

You could specify that a stylesheet is only loaded if the browser window has a maximum width of 800px. To do so, you simply extend the value of the media-attribute by the desired attribute and value when inserting the stylesheet. To get our example to work we need to use the following HTML-Code:

As an alternative you could also write it into the stylesheet directly: @media screen and (max-width: 800px) { ... } If you're working with Drupal (which you should), you can use the regular .info file of the theme you're using: stylesheets[screen and (max-width: 800px)][] = style.css

Writing the above HTML-Code () directly into page.tpl.php would be also possible, but this is not a clean way and thus not "the Drupal way". Stylesheets should be called from the .info file and most likely your regular stylesheet is already being called from there. Media Queries in Drupal can also be called in the function drupal_add_css(). <?php drupal_add_css('/path/to/my.css', 'module', 'screen and (max-width: 800px'); ?>

Of course this is not limited to using the width of the browser window as an attribute. E.g. there are height, width, orientation, color and resolution. All allowed attributes and the correct way of using them can be found at Media Queries (Media Features.

To get a glimpse of how it works check out this very site, undpaul.de. As soon as the browser window gets resized to a width of less than 980px, the right sidebar jumps below the main content and the header and logo get smaller. When getting below 820px width, the header gets even smaller.

Another positive side effect comes for free: when viewing the site on mobile devices, it looks much more structured, because the right sidebar blocks are no longer taking up space in the main content.

I should mention one drawback: users of browsers that do not understand CSS3 (which are Internet Explorer up to version 8, Firefox < 3.x) cannot benefit from this feature. There is a script (css3-mediaqueries.js), which enables media queries for those browsers, but we haven't tested it yet. I also do not see it as best practice to load more JavaScript for every little feature.