Sass media queries mixins

A Sass media queries mixin to avoid duplicating CSS breakpoints all over the place.

David Dal Busco
Geek Culture
Published in
3 min readDec 22, 2022

--

Photo by Luca Bravo on Unsplash

There are few gems we have implemented in NNS-dapp that makes our devs life easier on daily basis. One of these has been implemented my colleague Maskims Strasinskis: a Sass media queries mixins that makes us avoid duplicating CSS breakpoints all over the place.

​Foreword

​CSS media queries are handy but, as the app or design system grows, their usage grows as well exponentially which ultimately, makes the UI hard to maintain and difficult to refactor or re-work.

@media (min-width: 300px) {
background: red;
}

​Imagine having not one but, hundred of above breakpoints in your zillion of CSS files. If one day the design changes, you might have to run a gigantic search and replace to adapt your code.

​That’s where my colleague tricks becomes handy.

Mixins

Sass mixins allow you to define styles that can be re-used throughout your stylesheet. They make it easy to avoid using non-semantic classes, and to distribute collections of styles in libraries (source).

​In other words, mixins are functions that can be used to replicate the same styles multiple times in your apps or libs without the need to duplicate the code.

I​n this way, the idea is to create a function that generates the breakpoints but obfuscate their values. That’s why, the solution begins with the definition of Sass variables which define these sizes — e.g. the following within a _media.scss​ file.

$breakpoint-xsmall: 320px;
$breakpoint-small: 576px;
$breakpoint-medium: 768px;
$breakpoint-large: 1024px;
$breakpoint-extra-large: 1300px;

​Once the breakpoints defined, within the same file we can implement the effective mixins that maps a shorthand variable — e.g. small​ — with the size that we declared once (previous code).

@mixin min-width($breakpoint) {
@if ($breakpoint == xsmall) {
@media (min-width: $breakpoint-xsmall) {
@content;
}
} @else if ($breakpoint == small) {
@media (min-width: $breakpoint-small) {
@content;
}
} @else if…

--

--

David Dal Busco
Geek Culture

Freelancer by day | Creator of Juno.build by night