Order of media queries matters

Order of anything in CSS matters because of the cascade. Media queries are not an exception. I would like us to look at the example. It will help us understand the precedence of media queries: https://codepen.io/tonkec/pen/NZqbRQ

Container will be yellow on all the screen sizes except the one less than 400px and bigger than 320px. When it gets to that interval, this code will be applied, container will be blue from 320px to 399px:

1
2
3
4
5
@media (min-width: 320px) {
.container {
background-color: #2bc1bc; // blue
}
}

If we make our window smaller than 320px, the container will be black then. That color is set in the global styles, outside of media query:

1
2
3
4
5
.container {
width: 400px;
height: 50px;
background-color: #292929;
}

If we start widening our window from 400px all the way to 2000px, we can see that the container becomes yellow. But didn’t we set the background-color to green on 768px? Yes, we did, but that media query gets overwritten by the media queries that come after. It was overwritten first by this

1
2
3
4
5
@media (min-width: 1200px) {
.container {
background-color: #962bc1; /* purple */
}
}

and then by the

1
2
3
4
5
@media (min-width: 400px) {
.container {
background-color: #ffdc2e; /* yellow */
}
}

Hm so what did this example show us? It showed us that the order of media queries matters. The media query with breakpoint set to 400px overwrote those set to 768px and to 1200px because it comes after those breakpoints.

1
2
3
4
5
@media (min-width: 400px) {
.container {
background-color: #ffdc2e; /* yellow */
}
}

Let’s order them now ascending: https://codepen.io/tonkec/pen/JQdveR
The background-color will be black if the window is smaller than 320px, yellow if it is bigger than or equal to 400px, green if it is bigger than or equal to 768px and purple if it is bigger than or equal to 1200px.

My two cents are to be careful how are we going to order media queries