Home  >  Article  >  Web Front-end  >  How Can I Make Min-Width Media Queries Cascade Correctly?

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

Susan Sarandon
Susan SarandonOriginal
2024-11-16 01:57:02954browse

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.

The above is the detailed content of How Can I Make Min-Width Media Queries Cascade Correctly?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn