Search code examples
csssassmedia-queries

Grouping styles by selector or media query first


Imagine we have a stylesheet with two classes, a and b, each with styles changing at a certain breakpoint:

.a {
  //styles
}

.b {
  //styles
}

@media (max-width: 768px) {
    .a {
      //mobile styles
    }
    .b {
      //mobile styles
    }
}

These are grouped by breakpoint. Is it ever preferred to group them by selector instead? i.e:

.a {
  //styles
}

@media (max-width: 768px) {
  .a {
    //styles
  }
}

.b {
  //styles
}

@media (max-width: 768px) {
  .b {
    //styles
  }
}

The second looks a bit uglier, but that could easily be corrected with scss nested media queries. My concern with the former pattern is that it can encourage developers to edit one section of styles without taking a look at how a style change may affect its counterparts at other breakpoints. However, the former may be more useful for developers working on problems that appear only at specific screen sizes.

Would love to hear any thoughts or schools of thought with regard to this conflict of grouping - I've been looking for any resources on Smashing Magazine or CSS tricks but haven't come up with anything.


Solution

  • After doing ample research, I've personally arrived at this answer

    1. Keeping the styles for the same selector at different breakpoints is good for the developer experience - it keeps CSS more maintainable to be able to see a selector's behavior at every breakpoint all in the same place.
    2. In vanilla CSS, the pattern for doing this can be a bit ugly and unwieldy - if it's not minified, it can also lead to some performance issues due to duplicate media queries. Ruling: avoid grouping selectors and their media query counterparts in vanilla CSS - it's probably more trouble than it's worth.
    3. If you're using SCSS, absolutely nest your media queries inside your selectors. It's clean and more maintainable. With the right compilation you avoid duplicate media queries, avoiding the earlier discussed performance issues. Learn more here