Search code examples
csssassmedia-queriesless

Nesting @media rules in element


Is it a good practice to nest @media rules for each class separately or is it better to create @media and nest all classes inside?
Which method is more efficient in terms of speed of loading pages?

/* 
 * Sass or Less 
 */

/* example_1 */
.class1 {
  width: 100%;

  @media screen and (min-width: 740px) { 
    width: 50%;
  }
}

/* example_2 */
.class1 {
  width: 100%;
}

.class2 {
  color: #000;
}

@media screen and (min-width: 740px) { 
  .class1 {
    width: 50%;
  }

  .class2 {
    color: #faa;
  }
}

Solution

  • I think that it depends on the amount of the code you are going to write. It works without any problem, but hundreds of different media queries nested in each class could be hard to maintain. In my opinion a good practice, especially for big projects, would be to use separate files for each media query threshold, in order to keep your CSS organized as much as possible. For example:

    style.less

    .class1 {
      width: 100%;
    }
    
    .class2 {
      color: #000;
    }
    
    @media screen and (min-width: 740px) { 
      @import "min740.less";
    }
    

    min740.less

    .class1 {
      width: 50%;
    }
    
    .class2 {
      color: #faa;
    }
    

    If you are going to write separate components, like buttons or typographies, you can keep all the related media queries in the same file, in order to have a completely separate CSS module (your 2nd example basically).

    In terms of speed and performances, obviously is always recommended to use compiled LESS in production, but considering your examples, the single media query selector would be more efficient, since in the "example1 way" the media query selector will be replicated multiple times:

    .class1 {
      width: 100%;
    }
    @media screen and (min-width: 740px) {
      .class1 {
        width: 50%;
      }
    }
    .class2 {
      width: 100%;
    }
    @media screen and (min-width: 740px) {
      .class2 {
        width: 50%;
      }
    }