Last Updated: February 25, 2016
·
1.491K
· mulhoon

Cleaner SCSS Media Queries

There are multiple ways to handle CSS media queries. Here are a few options...

Queries everywhere

This isn't great as it adds a lot of repetitive code and, obviously if you want to change the breakpoint, you'll have to go through all your code.

.mydiv{
    max-width: 920px;
    @media only screen and (max-width: 768px) {
        max-width: 80%;
    }
    @media only screen and (max-width: 480px) {
        max-width: 100%;
    }
}

Mixins

This is almost there as we have a reusable mixin, but we're adding @include break-point( all over the place when all I really care about is 'mobile' or 'tablet'.

$tablet: 768px;
$mobile: 480px;
@mixin break-point($w) {
    @media only screen and (max-width: $w) { @content; }
}
.mydiv{
    max-width: 920px;
    @include break-point($tablet){
        max-width: 80%;
    }
    @include break-point($mobile){
        max-width: 100%;
    }
}

Simpler Mixins

This is my preferred method. We only need a couple of mixins, so I don't think it's worth using variables for the widths, unless you plan to use the widths elsewhere in your CSS.

@mixin mobile() {
    @media only screen and (max-width: 480px) { @content; }
}

@mixin tablet() {
    @media only screen and (max-width: 768px) { @content; }
}

.mydiv{
    max-width: 920px;
    @include tablet(){
        max-width: 80%;
    }
    @include mobile(){
        max-width: 100%;
    }
}

Can we get any cleaner? Let me know...

2 Responses
Add your response

I prefer not to use nesting MQ in CSS preprocessors at all, because they produce a lot of replicated output in CSS. So, in my opinion, cleaner way - is not to nest them and define selectors manually in MQ block.

over 1 year ago ·

I know what you mean. I would prefer not to have replicated CSS, but in practice, on large projects I find myself working on one element at a time, across all platforms. So it's helpful to have the style for one element grouped together and saves scrolling up and down or flipping between different scss files. In the end the css is compacted anyway so I try not to worry about any excess replication as long as it's clean and clear in the SCSS.

It really should be a feature of SASS compiling (to group the queries) as is discussed here https://github.com/nex3/sass/issues/116

over 1 year ago ·