One of the first things I do when I start a new CSS project, is define a helper for simplifying media queries. For example, with SASS, I like to be able to do something like this:
1 | .site-wrapper { |
The for_breakpoint
mixin would wrap its contents in a media query built from previously defined breakpoints.
I needed to do this in Stylus for this site. Here’s how I went about it:
First, I define the breakpoint media queries as a hash:
1 | media_queries = { |
Now, I define a mixin that takes a list of breakpoints and wraps its contents in a targeted media query:
1 | for_breakpoint(breakpoints) |
Important note: commas between media query conditions act as an or
. I always forget this.
Now we can do this for example:
1 | +for_breakpoint(mobile) |
Note: the +
is necessary when calling block mixins.
When compiled, the CSS will look like this:
1 | @media only screen and (max-width: 600px) { |
But we can also specify multiple breakpoints:
1 | .sidebar |
The above would compile to:
1 | .sidebar { |