Search code examples
csssassmedia-queries

Can @media be included in Scss partials below each element to speed up editing?


I just converted my css project over to scss and now that I am flipping back and forth between various partials I am wondering if it would just be easier to write my @media rules for an element right in the file below the corresponding selector, rather than at the bottom in a specific @media file?

For example the standard css method:

#header {
/* css style */
}
#nav{
/* css style */
}
.nav-container {
/* css style */
}
.
. 700+ lines of css...
.
@media screen and (max-width: 900px) {
#header {
/* new css style */
}
#nav{
/* new css style */
}
}

@media-queries screen and (max-width: 600px)*/
.nav-container {
/* new css style */
}
}

Versus what I would prefer to write in Scss partials:

_header.scss

#header {
/* css style */
}
// HEADER @MEDIA-QUERIES
@media-queries screen and (max-width: 600px)
/* new header css style */
@media-queries screen and (max-width: 400px)*/
/* new header css style */

_nav.scss

#nav {
/* css style */
}
.nav-container {
/* css style */
}
// NAV @MEDIA-QUERIES
@media-queries screen and (max-width: 600px)
/* new nav css style */
@media-queries screen and (max-width: 400px)*/
/* new nav css style */
/* new nav-container css style */

Is this second method an acceptable practice? Why or why not?

A similar question was asked 5years ago but only ever answered by a robot with advice that didn't seem very decisive. CSS media queries placement


Solution

  • Like the question you have linked says, the order does not matter so the second method is acceptable. But if you are using scss, there is even a better way because it allows you to nest your @media rules inside your selector. So you can even do this:

    #header {
      color: red;
      
      @media screen and (max-width: 600px) {
        color: blue;
      }
    }
    
    .nav-container {
      /* css style */
    
      @media screen and (max-width: 600px) {
        /* css style */
      }
    }
    

    The order does matter between individual @media rules. Like you should not place @media (max-width: 600px) after @media (max-width: 400px). See this