How to create a SASS (SCSS) mixin for responsive design
Despite CSS evolving and CSS-in-JS solutions becoming very popular, SCSS is still a very powerful styling solution for responsive web applications, especially when paired with css-modules.
Several studies show that most of the web traffic already comes from mobile devices and this number will continue to grow. This of course varies depending on your website or web application type, however it is very likely that responsive design plays a very important role in your project.
In this post we’ll be creating a responsive SCSS mixin that you can use in any project without having to remember how to use CSS media queries.
We’ll start off by defining the breakpoints for our design. I will be using the default Bootstrap (V5) breakpoints, however you can adjust them based on your needs.
First, we’ll create a SCSS map for storing those values:
Note that for the max values we subtract 0.02px. As mentioned in the Bootstrap docs this is because:
Browsers don’t currently support range context queries, so we work around the limitations of
max-prefixes and viewports with fractional widths (which can occur under certain conditions on high-dpi devices, for instance) by using values with higher precision.
Writing the mixin
Next, we’ll write a mixin that uses those breakpoints to produce the desired CSS media queries. It will receive two arguments:
- The breakpoint. It can be either one of the predefined values
xxlor some custom value (eg. 1000px or 520px)
- The direction, which determines if you want to go up or down — whether you are writing styles to be applied on smaller screen sizes or on larger ones. It can be
max(defaults to min).
That’s all! The mixin is ready to be used. Check some usage examples below.
Be careful with the order in which you write the mixins — the latest will always have the highest priority!