Write breakpoints and media queries using SCSS

Posts

When we work on a website we obviously have to take into consideration the “mobile” versions of our web project

Assuming you know what CSS media queries are, let’s see how to use the SCSS features to create beautifully readable media queries that keep your code clean and legible, which can be quickly reused in our SCSS files, and that are easy to use.

Set the code

Here is the code to create the mixins that we will use in the files.

// Breakpoints
$desktop: 1024px;
$tablet: 768px;

@mixin media($keys...) {
  @each $key in $keys {
    @if $key == phone {
      @media only screen and (max-width: $tablet - 1) {
        @content;
      }
    }
    @else if $key == tablet {
      @media only screen and (min-width: $tablet) and (max-width: $desktop - 1) {
        @content;
      }
    }
    @else if $key == desktop {
      @media only screen and (min-width: $desktop) {
        @content;
      }
    }
    @else if type_of($key) == number {
      @media only screen and (max-width: $key) {
        @content;
      }
    }
  }
}

Understanding the code

If you’re wondering why I used @each, the answer is very simple: if I’d only written the if and else-if series, I couldn’t have concatenated breakpoints.

Let’s say we want the background color of a div of a different color just for phone and tablet. If I hadn’t used @each, I would have had to write:

div {
  @include media(phone) {
    background-color: red;
  }
  
  @include media(tablet) {
    background-color: red;
  }
}

Using @each allows us to write this instead:

div {
  @include media(phone, tablet) {
    background-color: red;
  }
}

Moreover, if it happens a particular case where our breakpoints are not enough, we can customize the media queries by specifying pixels manually, thanks to @type-of(). For example:

div {
  @include media(1500px) {
    background-color: red;
  }
}

Please note that I have set my media queries according to how I use them. Personally I find it very convenient to use max-width as a limit, so you can set the overall style and then choose on which devices it should be changed.
This also happens if you manually enter a number of px. That number will be taken as max-width.

You can, of course, change their behavior according to your habits.