Search code examples
cssmedia-queriesbreakpoints

Advantages to using max-width as well as min-width in sequential media queries?


In a case where there are a clear series of breakpoints and related media queries, with each media-query altering the same property(s), is there any advantage to adding max-width values as well as min-width values?

For example is there any advantage to using:

@media (min-width: 300px) and (max-width: 599px) {
   color: red;
}
@media (min-width: 600px) and (max-width: 999px) {
   color: blue;
}
@media (min-width: 1000px) {
   color: green;
}

Instead of just:

@media (min-width: 300px) {
   color: red;
}
@media (min-width: 600px) {
   color: blue;
}
@media (min-width: 1000px) {
   color: green;
}

To clarify, I understand that I can target a range by adding a min and max width, but I'm referring to situations where breakpoints are sequential and based on width. Given that the next value in the sequence will override (trump) the previous, is there any reason to explicitly declare a range.


Solution

  • Specifying both min-width and max-width allows you to create blocks of rules that are mutually exclusive. The advantage is that you can specify the media queries in any order. The disadvantage is that you need to repeat the CSS rules more often. Example:

    /* order of media queries does not matter */
    @media (max-width: 299px) {
        #section-1 { display: none; }
        #section-2 { display: none; }
    }
    @media (min-width: 300px) and (max-width: 599px) {
        #section-1 { display: block; }
        #section-2 { display: none; }
    }
    @media (min-width: 600px) {
        #section-1 { display: block; }
        #section-2 { display: block; }
    }
    

    Specifying only min-width or max-width allows you to create blocks of rules that can cascade across multiple breakpoints. The advantage is that you can write CSS rules inrementally with minimal repetition. The disadvantage is that the media queries need to be sorted ascending (for min-width) or descending for (max-width), otherwise you run into WTFs. Example:

    /* mobile first */
    #section-1 { display: none; }
    #section-2 { display: none; }
    @media (min-width: 300px) {
        #section-1 { display: block; }
    }
    @media (min-width: 600px) {
        #section-2 { display: block; }
    }
    
    /* desktop first */
    #section-1 { display: block; }
    #section-2 { display: block; }
    @media (max-width: 599px) {
        #section-2 { display: none; }
    }
    @media (min-width: 299px) {
        #section-1 { display: none; }
    }