Media Queries – Kirby-style

Responsive web design and media queries are buzzing everywhere. I'm not going into detail on this. If you've never heard about it or you want to get started with responsive web design, you should take a look at the awesome tutorial series on netmagazine.com.

One way to make a website responsive is to load different CSS files for different screen sizes. That way it is quite easy to change the layout/css of your site depending on the current size of the screen.

This would typically looks somehow like…

<link rel="stylesheet" href="http://yourdomain.com/assets/styles/screen.css" />
<link rel="stylesheet" media="only screen and (min-width: 768px)" href="http://yourdomain.com/assets/styles/screen.768.css" />
<link rel="stylesheet" media="only screen and (min-width: 940px)" href="http://yourdomain.com/assets/styles/screen.940.css" />
<link rel="stylesheet" media="only screen and (min-width: 1220px)" href="http://yourdomain.com/assets/styles/screen.1200.css" />

Kirby gives you a nice shortcut for generating those stylesheet link tags, which you can use in your templates and snippets:

<?php

echo css('assets/styles/screen.css');
echo css('assets/styles/screen.768.css', 'only screen and (min-width: 768px)');
echo css('assets/styles/screen.940.css', 'only screen and (min-width: 940px)');
echo css('assets/styles/screen.1200.css', 'only screen and (min-width: 1220px)');

?>

There are two advantages about this approach:

It's shorter and you don't need to worry about absolute or relative URLs. Kirby will care about adding the correct URL in front of each stylesheet, so the links will never be broken.

Actually, you can use the second argument of the css() function for any kind of value for the media attribute. So if you are working with an additional print stylesheet, you can add it like this…

<?php

echo css('assets/styles/screen.css');
echo css('assets/styles/screen.768.css', 'only screen and (min-width: 768px)');
echo css('assets/styles/screen.940.css', 'only screen and (min-width: 940px)');
echo css('assets/styles/screen.1200.css', 'only screen and (min-width: 1220px)');
echo css('assets/styles/print.css', 'print');

?>