When it comes to your example, both CSS styles get applied since they possess equal specificity. In situations like this, the declaration that comes last takes precedence.
Specificity serves as a weight assigned to a particular CSS declaration, based on the number of each selector type in the matching selector. If multiple declarations have the same specificity, the one found last in the CSS will be applied to the element.
To observe the color swap between blue (<=2000px) and red (<=600px), resize your browser accordingly.
@media(max-width:2000px) {
html {
background-color:blue;
}
}
@media(max-width:600px) {
html {
background-color:red;
}
}
However, if you alter the order of these styles, it will always remain blue regardless of how narrow the viewport is, as even a width of 1px is still less than the 2000px max-width:
@media(max-width:600px) {
html {
background-color:red;
}
}
@media(max-width:2000px) {
html {
background-color:blue;
}
}
In certain cases, using min-width
could be more suitable. You can also utilize a combination of min-width
and max-width
:
@media all and (max-width: 699px) and (min-width: 520px)
Alternatively, you can establish a default style and only override it if the viewport reaches a certain width:
html {
background-color:red;
}
@media(min-width: 600px) {
html {
background-color:blue;
}
}