Search code examples
cssperformancelessmedia-queries

LESS, Media Queries, and Performance


I recently got started with LessCSS, and I've been having quite a bit of success in regards to how clean and readable my CSS has become. However, I don't think I'm using Less to its fullest advantage.

I'm now in the process of coding up my first fully-responsive site using Less, and I'm concerned with performance and speed. One thing to note is that I don't stick to a "breakpoint" methodology - I scale things up and down until they break, then I write CSS to fix them; which usually results in anywhere from 20 - 100 media queries.

I'd like to start using Less to nest the media queries inside my elements, such as the example below:

.class-one {
    //styles here

    @media (max-width: 768px) {
        //styles for this width
    }
}
.class-two {
    //styles here

    @media (max-width: 768px) {
        //styles for this width
    }
}

Through my initial testing, I have found that when reviewing the compiled CSS output - this methodology results in multiple (many!) instances of @media (max-width: ___px). I have scoured the internet, and haven't found anything that explicitly explains the performance implications of nesting/bubbling media queries.

Update 1: I realize that more CSS information results in a larger CSS file to download - but I'm not as worried about site load time as a sole metric. I'm more interested in the browser's handling of memory and performance after the DOM is ready.

Update 2 & Semi-Solution: I found this article which discusses the four main categories of CSS selectors and their efficiencies. I highly recommend the read which helped me sort out how best to tackle my over-media-query'd CSS.

So my question is this: after the DOM is ready, will having this many media queries in my compiled stylesheet affect load times & performance?


Solution

  • Its almost impossible to give you a totally accurate answer.

    When asking about performance the typical answer is to profile it and see what you get. Fix the slowest part first, then repeat.

    You can profile CSS selectors in the Chrome Developer tools:

    enter image description here

    Ultimately I don't think the media queries will have anywhere near as much impact on performance compared to even a slightly complicated selector.

    You can see more information about writing efficient CSS here:

    https://developers.google.com/speed/docs/best-practices/rendering

    Also with regards to file size and repeated CSS, gzip almost completely nullifies this as the gzip algorithm works best with repeated data.