Rethinking Sass media queries

in code


A look around told me that most Sass media query solutions fall into the pattern of a mixin that either calls a mixin, or from a list of preset variables. Mine looks like this:

@mixin media($args) {
    $type: nth($args, 1);
    $start: null;
    $end: null;

    @if $type == max {
        // Can't interpolate a mixin, so it becomes a long chain of if/else.
        @include max($start) {
            @content;
        }
    }
}

@mixin max($size) {
    // One of many mixins.
    @media screen and (max-width: $size) {
        @content;
    }
}

So, three problems:

  1. Preset mixins support only a subset of media queries, usually stuff like max-width, min-height and so on.
  2. Preset variables just aren’t a great solution. It doesn’t encourage variety, and the solution is specific to the project.
  3. Preset units rely on px. Where’s the love for rem or vw? I’d never use them, but still.
  4. A nested mess of mixins or variables is a pain to remember. It becomes a long list of possible values that I have to call in specific order.

I’ve begun a refactor with the idea of passing pithy keywords, in any order, to a mixin. These keywords are parsed into a query condition:

selector {
    @include media(width max 300px, height min 400px) {
        @content 'hello, world';
    }
}

selector {
    @media only screen and (max-width: 300px) and (min-height: 400px) {
        @content: 'hello, world';
    }
}

I’ve retained some support for the old mess of mixins in the form of a map that holds preset conditions:

selector {
    @include media(smartphone) {
        @content 'goodbye, world';
    }
}

selector {
    @media only screen and (min-device-width: 320px) and (max-device-width: 667px) {
        @content: 'goodbye, world';
    }
}

It’s different, and right now broken-y. It’s working great for simple queries on this site right now, and in the next few days I’ll throw some complex queries at it. GitHub:

https://github.com/bhalash/scss-helpers/blob/media-refactor/_media.scss



Decompression

in me


Your email address will not be published. Required fields are marked *