"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to make the minimum width media query correctly cascade?

How to make the minimum width media query correctly cascade?

Posted on 2025-04-18
Browse:209

How Can I Make Min-Width Media Queries Cascade Correctly?

Cascading CSS Specificity with Min-Width Media Queries

When designing a website, it is common practice to use responsive web design principles, including the mobile-first approach. This requires the use of min-width media queries to target devices of specific screen sizes. However, it can be confusing when overwriting CSS values for higher screen resolutions, as the lower min-width seems to take precedence.

This is because media queries are evaluated in order from least restrictive to most restrictive. In the example provided:

@media only screen and (min-width: 600px) {
    h2 { font-size: 2.2em; }
}

@media only screen and (min-width: 320px) {
    h2 { font: normal 1.7em/2.1em Helvetica, sans-serif; }
}

Both media queries are true when the screen width is 600px or greater. However, the second rule occurs later in the cascade, so it takes precedence and the smaller 1.7em font size is applied.

Resolution

To effectively overwrite declarations in higher resolutions using min-widths without resorting to stronger selectors or max-width, you can switch the order of your media queries:

@media only screen and (min-width: 320px) {
    h2 { font: normal 1.7em/2.1em Helvetica, sans-serif; }
}

@media only screen and (min-width: 600px) {
    h2 { font-size: 2.2em; }
}

This ensures that the larger font size is applied when the screen width is at least 600px. This will give you the cascading specificity you expect, with the higher min-width taking precedence.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3