官术网_书友最值得收藏!

Combine media queries or write them where it suits?

I'm a fan of writing media queries underneath the original 'normal' definition. For example, let's say I want to change the width of a couple of elements, at different places in the style sheet, depending upon the viewport width I would do this:

.thing {
    width: 50%;
}

@media screen and (min-width: 30rem) {
    .thing {
        width: 75%;
    }
}

/* A few more styles would go between them */

.thing2 {
    width: 65%;
}

@media screen and (min-width: 30rem) {
    .thing2 {
        width: 75%;
    }
}

This seems like lunacy at first. We have two media queries that both relate to when the screen has a minimum width of 30rem. Surely repeating the same @media declaration is overly verbose and wasteful? Shouldn't I be advocating grouping all the identical media queries into a single block like this:

.thing {
    width: 50%;
}

.thing2 {
    width: 65%;
}

@media screen and (min-width: 30rem) {
    .thing {
        width: 75%;
    }
    .thing2 {
        width: 75%;
    }
}

That is certainly one way to do it. However, from a maintenance point of view I find this more difficult. There is no 'right' way to do this but my preference is to define a rule for an individual selector once and have any variations of that rule (such as changes within media queries) defined immediately after. That way I don't have to search for separate blocks of code to find the declaration that is relevant to a particular selector.

Note

With CSS pre and post processors, this can be even more convenient as the media query 'variant' of a rule can be nested directly within the rule set. There's a whole section on that in my other book Sass and Compass for Designers.

It would seem fair to argue against the former technique on the grounds of verbosity. Surely file size alone should be enough reason not to write media queries in this manner? After all, no one wants a big bloated CSS file to serve their users. However, the simple fact is that gzip compression (which should be compressing all the possible assets on your server) reduces the difference to a completely inconsequential amount. I've done various tests on this in the past so if it's something you would like to read more about, head over to: http://benfrain.com/inline-or-combined-media-queries-in-sass-fight/. The bottom line is, I don't believe you should concern yourself with file size if you would rather write media queries directly after the standard styles.

Tip

If you want to author your media queries directly after the original rule but have all identical media queries definitions merged into one, there are a number of build tools (at the time of writing, Grunt and Gulp both have relevant plugins) that facilitate this.

主站蜘蛛池模板: 巨野县| 唐海县| 林芝县| 延边| 清镇市| 卢氏县| 萨嘎县| 中牟县| 馆陶县| 阳东县| 高平市| 阜康市| 博白县| 辽宁省| 衡阳市| 通州区| 南靖县| 榆中县| 泽库县| 武宁县| 江北区| 玉溪市| 马公市| 柳林县| 阿尔山市| 永昌县| 东乡| 青河县| 曲阳县| 石城县| 沂南县| 九江市| 垦利县| 德兴市| 珠海市| 旺苍县| 苏尼特右旗| 龙陵县| 彭州市| 大港区| 密山市|