Search code examples
csssassmedia-queries

Is there an advantage in grouping css media queries together?


(this may have been answered already - couldn't find the answer though)

The traditional @media query override tends to group all the override for one size/medium under the same bracket group.

e.g.

.profile-pic {
    width:600px;
}
.biography {
    font-size: 2em;
}

@media screen and (max-width: 320px) {
    .profile-pic {
        width: 100px;
        float: none;
    }
    .biography {
        font-size: 1.5em;
    }
}

In Sass, there's a really nifty way to write @media query overrides within the nested declaration, like so:

.profile-pic {
width:600px;
  @media screen and (max-width: 320px) {
    width: 100px;
    float: none;
  }
}

.biography {
    font-size: 2em;
  @media screen and (max-width: 320px) {
    font-size: 1.5em;
  }
}

now, when compiled, sass doesn't group the @media query blocks together, so the output ends up being something like this:

.profile-pic {
    width:600px;
}
@media screen and (max-width: 320px) {
  .profile-pic {
    width: 100px;
    float: none;
  }
}

.biography {
    font-size: 2em;
}
@media screen and (max-width: 320px) {
  .biography {
    font-size: 1.5em;
  }
}

I've used this technique for a recent project and when you apply that principle to a much bigger project you end up with multiple @media query section disseminated throughout your css (i've got about 20 so far).

I quite like the sass technique as it makes it easier to follow the flow of overrides (and also makes it easier to move things around).

However, I'm wondering if there is any disadvantage in having multiple @media section through the CSS, particularly performance wise?

I've tried the chrome css profiler but I couldn't see anything specific to @media queries.

(More info on @media in sass on this page)


Solution

  • A bit late to the party, but based on the tests below the performance impact seems to be minimal. The test shows the rendering times for an example page with 2000 separate and combined media queries, respectively.

    http://aaronjensen.github.com/media_query_test/

    The main benefit seems to be in file size more than anything else - which, if you're compressing your CSS for production, will be substantially reduced anyway.

    But ultimately, as the linked post below puts it:

    "If you have 2000+ media queries in your CSS, I think that you may want to reconsider your UI development strategy versus using a gem to re-process your CSS."

    Blog post detailing the issue: https://web.archive.org/web/20140802125307/https://sasscast.tumblr.com/post/38673939456/sass-and-media-queries