Web Development Concepts with Ebinabo

Web Development Concepts with Ebinabo

One Less Media Query with SCSS

One Less Media Query with SCSS

Subscribe to my newsletter and never miss my upcoming articles

This article assumes that you have a basic knowledge of SCSS and it describes some syntactical sugar to help simplify your workflow as regards media queries. If you don't have a lot of experience with SCSS and want to know how this could help structure your code better, feel free to continue this article, you might also want to peep the documentation.

If you're using VSCode, Live Sass Compiler does well to compile your scss code and add vendor prefixes for you.

Media queries are a great way to control how elements are displayed on screen depending on the size of the screen. However, with multiple elements in the DOM tree all needing to displayed differently it could get you writing a lot of media queries.

What if all our media queries could be centralized and be made to be more readable. Well it's possible and we would be using SCSS for that. The particular features we would be using are @mixins and @content.

We would just need to declare this at the top of our .scss file or save it in another file and import it.

@mixin for-phone-only {
    @media (max-width: 599px) { @content; }
}
@mixin for-tablet-portrait-up {
    @media (min-width: 600px) { @content; }
}
@mixin for-tablet-landscape-up {
    @media (min-width: 900px) { @content; }
}
@mixin for-desktop-up {
    @media (min-width: 1200px) { @content; }
}
@mixin for-big-desktop-up {
    @media (min-width: 1800px) { @content; }
}

These mixins are named according to the screen sizes they affect and it's easier to globally change the screen size of any of the viewports easily.

Now anytime you want to use any of the mixins in your main scss file, you would just need to declare them as follows:

@include for-phone-only {
    body {
        font-size: 24px;
    }
}

This would change the font-size on mobile devices to 24px and would render in the css file as:

@media (max-width: 599px) {
    body {
        font-size: 24px;    
    }
}

Notice how the max-width on the media query matches the original max-width set in the mixin above.

This is a very basic implementation of this feature, it's possible to write more complex media queries such as:

@mixin for-larger-portrait-screens {
    @media (min-height: 680px), screen and (orientation: portrait) { @content; }
}

You could go through the documentation on using media queries and find out what's possible and you can write mixins for all of them. All that's left now is proper semantics.

Now you have more readable SCSS code. It's not the most important feature but hey, you could never go wrong in sprinkling some sugar on your scss code.

 
Share this