Using variables in @media queries
One thing that I’ve discovered recently after playing with a little bit of responsive web design with Sass, is that it would extremely useful to use variables to store the @media query string to help with encapsulation.
Why?
The media queries we’re using to modify our layouts are becoming more robust and numerous. We have queries for mobile, tablets, wide-screen, landscape, portrait and of course, standard displays.
@media screen and (min-width: 1700px)
{
body
{
font-size: 1.3em;
}
}
@media (max-width:1024px)
{
body
{
font-size: 1.1em;
}
.article
{
width: 35em;
}
}
While these are all really just different screen widths, our layout might change significantly at a certain point to accommodate the new screen real estate in a more usable way.
Preferably we’d only write each of these media query blocks once. But if we’re properly encapsulating our components we don’t want to mix out components into a single media query. That wouldn’t be very DRY now would it?
Here’s an example component I’m using to let me know which layout is being used (using media queries). It’s positioned at the top of the window, and the content changes based on the current query that is being satisfied:
#debug
{
position:absolute;
top:0;
left:0;
color:#fff;
content: ' ';
}
@media screen and (min-width:1025px)
{
#debug::after
{
content: 'Normal';
}
}
@media (max-width:1024px)
{
#debug::after
{
content: 'Tablet';
}
}
@media screen and (min-width: 1700px)
{
#debug::after
{
content: 'Wide-screen';
}
}
/* Normal Styles */
@media screen and (min-width:1025px)
{
body
{
font-size: 1.2em;
}
.article-main
{
width: 45em;
}
}
And so on. These are points in my design where the layout changes drastically. Whether the layout is fluid or fixed doesn’t particularly matter, as different items might float, un-float, clear etc. to form the new layout.
What if I decide to change the ‘normal’ or ‘tablet’ width to something else later on? I can either squeeze all of my components into the single query, or write the same query twice.
I’d like to be able to do this SASS variables:
#debug
{
position:absolute;
top:0;
left:0;
color:#fff;
content: ' ';
@media $media_screen
{
&
{
content: 'Normal';
}
}
@media $media_tablet
{
&
{
content: 'Tablet';
}
}
}
Perhaps there’s a better way to implement something like this that I’m not seeing, but I think this could be an elegant solution to help encapsulate @media queries.