Writing on the principles & practice of building digital products

Micro Media Query Mixin

The worlds smallest media query mixin ™. It's not perfect, but 90% of the time it's good enough.

I've used a few different methods for dealing with media queries over the years, some more complicated than others. However more often than not all I need to do is change styles between two screen widths. By saying that I acknowledge that the Micro Media Query Mixin doesn't take into account device heights, screen densities and many other things, but for me it's works well enough most of the time. So without further ado, here it is:

The mixin

// ---------------------------------
// Media query breakpoints & mixin
// 
// Usage: 
//
// @include mq("BREAKPOINT_NAME") { //styles } 


$breakpoints: (
  "extra-small" 500px,
  "small" 700px,
  "medium" 1047px,
  "large" 1300px,
  "extra-large" 1450px,
  "extra-extra-large" 1800px
);

@mixin mq($size, $type: "min-width") { 
  @each $breakpoint in $breakpoints {
    @if ($size == nth($breakpoint, 1)) {
      @media ($type: nth($breakpoint, 2)) {
        @content;
      }
    }
  }
}

That's it. Small and (hopefully) to the point. The mixin defaults to a mobile-first, min-width approach to media queries. So basically you define the mobile styles first then add adjustments for larger screens.

Usage

.header {
  // Mobile styles first...
  padding: 1em;

  @include mq("medium") {
    // Add more padding for medium size screens...
    padding: 2em;
  } 

  @include mq("large") {
    // And yet more on large screens
    padding: 3em;
  } 
}

If you wanted to go for a desktop-first approach, it's as simple as including a second max-width parameter:

@include mq("medium", "max-width") {
  // Styles
} 

Approach

For breakpoint naming I've erred away from device names to more arbitrary small, medium, large. I chose these over the shorter s, m, l as it's easier to decipher what the code does at a glance using the longer names. s can quickly become meaningless if you haven't looked at the code for a while.

The breakpoints are defined as a multidimentional Sass list. I've used lists rather than maps, as lists work on older versions of Sass (3.2 and below), making the mixin more widely compatible.

Fin.

And that's pretty much that. As I say it's simple and won't cover everything, but the majority of the time it's good enough for me.

If you'd like to know more about Sass lists, check out Hugo Giraudel's Understanding Sass lists. Also Chris Coyier's Logic in Media Queries is a great place to learn about building more complex media queries.