Inigo
Inigo

Reputation: 8685

Performance impact of multiple responsive declarations

I am not entirely sure of the best way to place declarations such as

@media screen and (max-width: 600px) {
     //
}

in my stylesheet. If, for example, I have a block of rules pertaining to some element (say, the sidebar) and I want to include some responsive rules with it, then it is tempting to insert the above code along with all the other rules for the sidebar. But then I might have some other element (say, the header) that also needs to change in some way when the screen width is below 600px. Then I'll end up with several @media screen and (max-width: 600px) declarations scattered up and down my CSS file. But it makes more sense- to me- to prioritize grouping together CSS rules according to the HTML elements they control.

So can I do this? Is there a negative performance impact from having

@media screen and (max-width: 600px) {
    .sidebar {
        font-size: 12px;
    }
}

@media screen and (max-width: 600px) {
    .header {
        font-size: 16px;
    }
}

rather than

@media screen and (max-width: 600px) {
    .sidebar {
        font-size: 12px;
    }
    .header {
        font-size: 16px;
    }
}

?

Upvotes: 0

Views: 67

Answers (2)

Nicolas Cava
Nicolas Cava

Reputation: 43

There is no notable loss of performance using several media queries instead of only one. However, if you resize or zoom-in/out your browser, there can be a peak of memory and CPU load. You will not resize your browser, but partially-sighted users needs to zoom your website, etc.

You should consider using a CSS Preprocessor like Less, SASS, or Stylus. A media query can be placed as a CSS property in your rule:

// app.less

@max-width: 600px;

.sidebar {
    background: #2c2c2c;
    @media screen and (max-width: @max-width) {
        font-size: 12px;
    }
}

If you can't use a CSS Preprocessor, then don't duplicate your media queries because of maintenance nightmare.

Upvotes: 1

Justin
Justin

Reputation: 149

I think it would just bulk up your css file size, but if you minify it, you should be fine. It is best practice though to accomplish as much as you can in as little code as possible.

Upvotes: 0

Related Questions