mq-func

Sass mixin for creating continuous functions from media queries

Usage no npm install needed!

<script type="module">
  import mqFunc from 'https://cdn.skypack.dev/mq-func';
</script>

README

mq-func

mq-func is a sass utility for creating continuous functions from media queries. It was inspired by this blog post.

Usage

Example

The package contains a single mixin mq-func which accepts a map of breakpoints with screen widths as keys and maps describing properties for each breakpoint as values.

@import "node_modules/mq-func/index.scss";

main {
  // The screen widths (map keys) here must be increasing.
  @include mq-func((
    500px: (width: 464px, font-size: 15px),
    600px: (width: 528px, font-size: 16px),
    1000px: (width: 660px, font-size: 20px)
  ), $const-upper: true);
}

The width of the main element will vary as follows:

  • Under 500px, it will be interpolated using the same slope as between 500px and 600px.
  • From 500px to 600px, it will vary linearly from 464px to 528px.
  • From 600px to 1000px, it will vary linearly from 528px to 660px.
  • Above 1000px, it will remain constant at 660px due to the const-upper argument.

The mixin will generate @media (min-width: <...>) queries accordingly:

main {
  width: calc(64vw + 144px);
}

@media (min-width: 600px) {
  main {
    width: calc(33vw + 330px);
  }
}

@media (min-width: 1000px) {
  main {
    width: 660px;
  }
}

Using CSS variables

CSS variables can be used instead of regular properties, for example to do additional computations afterwards.

:root {
  @include mq-func((
    500px: (--half-width: 3em),
    600px: (--half-width: 4em),
    700px: (--half-width: 4em)
  ));
}

main {
  width: calc(var(--half-width) * 2);
}

Using other media queries

Any media query that allows for the min-<value> such as min-width can be specified as a second argument to be used by the mixin instead of the width. Possible values include width (default), height , resolution, aspect-ratio, color-index, etc. Units will automatically be handled by the Sass engine.

@include mq-func((
  72dpi: (font-size: 3rem),
  150dpi: (font-size: 4rem),
  300dpi: (font-size: 5rem)
), $query: "resolution");